Architecture – Separation of construction and initialization

Architectureconstructionconstructorsinitializationobject-oriented-design

I'm confused by this post by Mark Seeman.

And his comment on IInitializable below:

The problem with an Initialize method is the same as with Property
Injection (A.K.A. Setter Injection): it creates a temporal coupling
between the Initialize method and all other members of the class.
Unless you truly can invoke any other member of the class without
first invoking the Initialize method, such API design is deceitful and
will lead to run-time exceptions. It also becomes much harder to
ensure that the object is always in a consistent state.

The same time he writes:

This issue is similar to the issue of invoking virtual members from
the constructor. Conceptually, an injected dependency is equivalent to
a virtual member.

I thinks this statement is true only if admit that constructed != initialized.

What we get now:
Dependencies are injected in constructor but it is not recommended to use them.
Initialize phase brings complexity and should be avoided.

Isn't it contradictory?

Imagine class needs to set its state using the provided dependencies. Loading saved setting for example.
Init is bad, constructor is bad, so where to perform this operation?

And another point:
Are not methods like Connection.Open() just another name for Initialize?

Question:
So can anyone describe a good initialization pattern in the context of Dependency Injection that addresses the concerns Mark Seeman brings up?

Best Answer

dedicated Initialise method is bad - if you use this you must construct an object and then not use it at all until you've successfully called Init, and always destroy it if the Init call fails. Its a mess of initialisation that is much better handled in the constructor.

If you only return a successfully constructed object that contains everything it needs to start working, then you have a much easier time as a programmer using that class.

Similarly, there shouldn't be a problem if the injected dependancy is resolved during construction.

However that means setting the DI object during construction - 'constructor injection', and I assume he's talking about 'property injection' where the config is passed in as a set of property calls after the object is constructed. This is the same problem where you had an Init method, but you now have a SetConfigX method. Names are different, obviously, but the principle is the same - you end up with a half-constructed object that you then fill out with the rest of its state before it can be used.

Related Topic