Wednesday, 12 March 2025

When to pass a dependency to a class?

I was speaking to another developer the other day and he insisted that if a class needs an instance of another class it should always be passed in an 'Init' method and not in the constructor. I disagreed with him on this and thought I should clarify when I think a dependency should be passed.

There are 2 options when passing a dependency to a class:

  1. Passing it as a parameter in the Create constructor.
  2. Passing it in a separate 'Init' method after creation. It does not have to be called 'Init'. 
When to use the 'Create' method and its advantages:
  • When the class absolutely needs the other class to operate properly.
  • Ensures the object is in a valid state immediately after creation.
  • Prevents accidental use of an uninitialized object.
  • Simplicity, it can lead to cleaner and more concise code.
When to use an 'Init' method and its advantages:
  • When the dependency could be seen as optional. The class can operate or partly operate without the other class. This can be done with the Create method, but passing it as nil.
  • Need delayed initialization.   
In most cases, the Create method (constructor) approach is preferred for better safety and reliability.