#Constructors
#Constructors
I recently read an article (which I sadly cannot find) about how Constructors should only be used for assignment.
I agree to an extent. I think it's fine to have a strictly private "Init" method that is responsible for "setting up" the object, such that you can safely use the object right after instantiation, without having to manually set it up through assignment on properties.
I might be misremembering the point of the article, but what is your thoughts on this?
I recently read an article (which I sadly cannot find) about how Constructors should only be used for assignment.
I agree to an extent. I think it's fine to have a strictly private "Init" method that is responsible for "setting up" the object, such that you can safely use the object right after instantiation, without having to manually set it up through assignment on properties.
I might be misremembering the point of the article, but what is your thoughts on this?
Probably this one: http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/ but there are countless other that say basically the same thing.
ReplyDeleteRegarding your "setting up" the object. Yes if we are talking about things like lists but not when we are talking about other dependencies that should be passed by ctor (if mandatory) or property (if optional) injection. See this one: http://misko.hevery.com/2008/09/30/to-new-or-not-to-new/
In the real world, time flies, and the state of a reality is always changing. In practice, this state change induces code complexity. During object modeling, we create "snapshot" of the reality, by defining properties of a given state.
ReplyDeleteSome programming patterns (e.g. the "Value Objects" defined in DDD) try to define read-only objects, with the constructor used to be the only way of setting properties values.
But there are other use cases. Sometimes, constructors are not available, e.g. if you use IoC and DI: you tend to use factories and abstract interfaces, instead of classes and fixed constructors. Using constructor may couple the code with a given class, whereas from abstraction (and SOLID principles) comes greater maintainability.
The problem simply comes down to this: you're correct, and the multiple lines of code to initiate Delphi objects is ungainly and hardly RAD. However, Delphi lacks named/optional parameters. This is what obligates the "big block of code" Delphi object initialization pattern.
ReplyDeleteIt would be great if we could do...
tweets := TwitterScan.Create(keyword="Obama", max_tweets:=70, retweets:=False);
...but we can't. I have seen that it's possible to do keyword parameters but it involves IDispatch and there are a lot of restrictions.
Named/optional parameters are on my short list of 3..5 things Delphi could add to really make beautiful APIs possible and give the language a fresher feel.