|Don't ask to ask, just ask|
Re^4: Perl Object Initilizationby armstd (Friar)
|on Jun 10, 2011 at 17:36 UTC||Need Help??|
Hmm, well maybe I'm just in violent agreement with the "partial initialization" camp here. I'm just more partial to less initialization. :)
I use a simple constructor, inherited by every package. It accepts random name-value pairs as arguments, stores them internally, and returns a blessed object. Nothing more. Usually "id" and reftype are all my objects need up front. I don't use anything like a UNIVERSAL::new(), because that implies too many assumptions about third party code operating in my ecosystem. My constructor does get inherited by all of my classes though, to deliver a consistent construction behavior and common method call syntax throughout my frameworks.
I don't presume in my constructor to know how the objects will be used in their lifetime. The only valid assumption in my use model is that construction has been requested. When a method gets called that requires initialization, then apparently a use model requiring initialization is being used, so initialization gets done then.
I've worked with abstracting SCM systems quite a bit like ClearCase and Perforce. In many cases, an object representing a file or version may not need to be initialized with the attributes from the database in order to be able to request the SCM system do something interesting or useful with that file. Self-identification is sufficient. Other custom integration operations in user space will want more inforamtion from the database in order to complete their task, and will trigger initialization.
One issue I used to have with having a half/half approach was inconsistency in maintenance. When developers saw initialization happening in the constructor, it was easy to just dump more stuff in there, slowing everything down. When there is "no" constructor available for initialization, and every method becomes responsible for whatever initialization it needs to operate properly, it's easier to maintain a consistent level of performance imo. Never doing more work than required at any point during execution.
It's absolutely preferable not to even construct objects that won't be used, but its hard to call methods on things that don't exist. Sufficiently abstracted frameworks cannot always make assumptions about use models.