On Sun, Apr 04, 2010 at 05:36:23PM -0500, Larry Garfield wrote: > Hi folks. Somewhat philosophical question here. > > I have heard, although not confirmed, that the trend in the Java world in the > past several years has been away from constructors. That is, rather than > this: > > class Foo { > public void Foo(Object a, Object b, Object c) {} > } > > Foo f = new Foo(a, b, c); > > The preference is now for this: > > class Foo { > public void setA(Object a) {} > public void setB(Object b) {} > public void setC(Object c) {} > } > > Foo f = new Foo(a, b, c); > f.setA(a); > f.setB(b); > f.setC(c); > > I suppose there is some logic there when working with factories, which you > should be doing in general. However, I don't know if that makes the same > degree of sense in PHP, even though the OO models are quite similar. > > 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.) By the way, I've found this to be a problem in C++ as well. I personally prefer not to have to pass parameters to a constructor, but even in C++, doing so seems a simpler solution than relying on the programmer to remember to call the proper setters. 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 -- Paul M. Foster -- PHP General Mailing List (http://www.php.net/) To unsubscribe, visit: http://www.php.net/unsub.php