IPB
Your Ad Here


Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
Antipattern: the verbose constructor
admin
post Jul 31 2008, 05:46 PM
Post #1


Administrator
***

Group: Root Admin
Posts: 49,777
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
Go to the top of the page
 
+Quote Post

Reply to this topicStart new topic
Tags
No Tag inserted yet

1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



RSS Lo-Fi Version Time is now: 21st November 2009 - 04:25 PM
Your Ad Here