Skip to content

Issues in Dependency Injection article #172

@danthe1st

Description

@danthe1st

The article on Dependency Injection will turn one year tomorrow.

That being said, there are a few issues I see with that article:

  • The last codeblock at the end of the article declares an BeanFactory beanFactory = BeanFactory.INSTANCE; which is not used since it uses BeanFactory.INSTANCE.getInstanceOf(...) as opposed to beanFactory.getInstanceOf(...).
  • In the "Creating Singletons" section, the text mentions "Here is the class." but there are 6 paragraphs (not counting the "Here is the class." paragraph) until the class actually starts.
  • (more of a suggestion) While the "Creating Singletons" section mentions that this approach could create the multiple objects of a singleton (can it really be called a singleton if the DI framework allows creating multiple instances of it even if only one is actually used), this problem could be avoided by using computeIfAbsent which ensures that the lambda is not executed concurrently.
  • The same section also contains "For that, you can use a registry, implemented by a ConcurrentMap, that is a thread-safe extension of the Map interface." - I think it should use implementation instead of extension.
  • The code in the article introduces a potentially confusing side effect which is not mentioned at all: It is possible to create singleton instances with constructor parameters by calling the getInstanceOf() method with these parameters and these instances can then be used by later @Injects. However, @Inject cannot use constructor parameters leading to the following issues:
    • Assuming the singleton class has a constructor with arguments but no no-args constructor: If getInstanceOf() is called with the parameters before creating the objects, it can be used by @Inject but if the @Inject is executed first, it throws a NoSuchMethodException because the constructor is not found. This is dependent on the order of calls (and it's supposed to be thread-safe!).
    • If the singleton class has both a no-args constructor and a parameterized constructor that's called via getInstanceOf(parameters, here) which is also used by @Inject, the called constructor depends on the number of arguments. This can lead to issues that are hard to debug (wrong constructor sometimes called), especially in multithreaded environments.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions