Re: Constructor usage
| From: | Larry Garfield | Date: | Mon, 05 Apr 2010 04:59:29 +0000 |
| Subject: | Re: Constructor usage | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-303830@lists.php.net to get a copy of this message | ||
On Sunday 04 April 2010 09:21:28 pm Paul M Foster wrote:
> > So, I'll throw the question out. Who uses example 1 above vs. example 2
> > when writing dependency-injection-based OOP? Why? What trade-offs have
> > you encountered, and was it worth it?
>
> One problem I have with "parameterless constructors" is this: When you
> rely on setters to shape your object rather than the constructor, your
> other methods cannot assume the object is in proper shape to be usable.
> There's no guarantee the programmer won't forget one of the vital
> setters. So each method in the object must test to ensure the object can
> actually be used properly. This isn't a deal-breaker, but it seems like
> an awfully unnecessary piece of additional code which must be replicated
> in each method. (Naturally, this is moot where the class doesn't depend
> on any outside objects or parameters to operate.)
Yeah, I tend toward using constructors for injection for the same reason: That
way I always know for sure that if I have an object, it's "complete". I defer
most object instantiation to factories anyway, so in practice it's not a huge
issue for me.
> I've found that many of my classes require other classes in order to
> operate. Moreover, they must be instantiated in the proper order, or
> things fall apart. So I took the step of creating my own "dependency
> injection instantiator" class which handles all this for me. Classes
> with dependencies typically are specified so that the requisite objects
> are passed to the constructor (the simplest way). Each class which is
> managed by the DII is registered first, with whatever parameter or
> object dependencies needed. Then the DII's "instantiate()" method is
> called as needed for each object. The DII class handles instantiating
> objects in the proper order and with the proper dependencies. The
> programmer's job is made much simpler.
>
> Paul
Sounds overly complicated, but whatever works. :-) In my experience so far I
find that a well-designed factory is sufficient, but it may not be in larger or
more involved OO frameworks than I've used to date.
--Larry Garfield