Antipattern: the verbose constructor |
![]() ![]() |
Antipattern: the verbose constructor |
Jul 31 2008, 05:46 PM
Post
#1
|
|
|
Administrator ![]() ![]() ![]() Group: Root Admin Posts: 12,822 Joined: 9-May 08 Member No.: 1 |
Constructors are often used to shortcut dependency injection and parameter passing on instantiation. This is a valid practice and often leads to shorter code. Consider the following example (a simple value object, often used to not mess around with floats and to keep currency and amount together): class Money { protected $_amount; protected $_currency; protected $_divisor; public function __construct( $amount = null, $currency = null, $divisor = null) { if ($amount !== null) $this->setAmount($amount); if ($current !== null) $this->setCurrency($currency); if ($divisor !== null) $this->setDivisor($divisor); } ... setter and getter ... } Now consider instantiating this object. Instead of creating a new instance of “Money” and calling three setter, everything can be done compactly in the constructor. $money = new Money(13200, 'EUR', 100); So for the money object this works pretty well. The code is easy to read, but wait, the first argument can be grasped easily, the second too, but the third? It is not too obvious that it is a divisor is passed. An alternative would be changing the constructor to accept an array. This is a replacement for true named arguments, as e.g. Python supports. Solar uses that a lot, as well as the Zend Framework. $money = new Money( array( 'amount' => 13200, 'currency' => 'EUR', 'divisor' => 100 ) ); Much better readable but does your IDE code completion works? And what happens if you pass “amoµnt”, because your fingers are as clumsy as mine? Exactly, the parameter will be silently ignored. But look at this: $money = new Money(); $money->setAmount(13200); $money->setCurrency('EUR'); $money->setDivisor(100); It is at least equally short, readable,, your <span class="caps</body>"/> Truncated by Planet PHP, read more at the original (another 8475 bytes) -------------------- -------------------------------------------------------------------------------------------
AdGuru.org is a current happenings discussions board for Information Technology, News and Fun visit: www.adguru.org |
|
|
|
![]() ![]() |
|
Lo-Fi Version | Time is now: 6th January 2009 - 01:34 PM |