Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Object construction outside the constructor

When it comes to designing classes and "communication" between them, I always try to design them in such way that all object construction and composing take place in object constructor. I don't like the idea of object construction and composition taking place from outside, like other objects setting properties and calling methods on my object to initialize it. This especially gets ugly when multiple object try to do thisto your object and you never know in what order your props\methods will be executed.

Unforunatly I stumbl on such situations quite often, especially now with the growing popularity of dependecy injection frameworks, lots of libraries and frameworks rely on some kind of external object initialization, and quite often require not only constructor injection on our object but property injection too.

My question are:

  1. Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?

  2. Is ther some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)

like image 370
Alex Burtsev Avatar asked Sep 28 '11 05:09

Alex Burtsev


1 Answers

Is it ok to have objects that relly on some method, or property to be called on them after which they can consider them initialzied?

No. Init methods are a pain since there is no guarantee that they will get called. A simple solution is to switch to interfaces and use factory or builder pattern to compose the implementation.

@Mark Seemann has written a article about it: http://blog.ploeh.dk/2011/05/24/DesignSmellTemporalCoupling.aspx

Is there some kind of pattern for situations when your object acting is receiver, and must support multiple interfaces that call it, and the order of these calls does matter? (something better than setting flags, like ThisWasDone, ThatWasCalled)

Builder pattern.

like image 59
jgauffin Avatar answered Sep 18 '22 23:09

jgauffin