FAQ
overflow

Great Answers to
Questions About Everything

QUESTION

I have a class with quite a few attributes, most of which are known when I create an instance of the object. So I pass all the values in the constructor:

$op = new OpenIdProvider($imgPath . $name . $ext, 'openid_highlight', 
                         0, 0, 108, 68, 6, $info[0], $info[1], $name);

I'm finding that having this many parameters makes it confusing both when writing and reading the code, as it's not easy to determine which attribute each value corresponds to. Also, this has a bit of a code smell to it - seems like there should be a better way. Any suggestions?

{ asked by BenV }

ANSWER

Martin Fowler's bible book "Refactoring" does identify a smell called "Long Parameter List" (p78) and proposes the following refactorings:

Of these I think that "Introduce Parameter Object" would best suit:

You'd wrap the attributes up in their own object and pass that to the constructor. You may face the same issue with the new object if you choose to bundle all the values directly into its' constructor, though you could use setters instead of parameters in that object.

To illustrate (sorry, my php-fu is weak):

$params = new OpenIDParams();
$params->setSomething( $imgPath . $name . $ext );
$params->setSomethingElse( 'openid_highlight' );

.. snip ..

$params->setName( $name );

$op = new OpenIdProvider( $params );


This is a little more verbose but it addresses your concern about not being clear about the attributes' purpose / meaning. Also it'll be a little less painful to add extra attributes into the equation later.

HTH

{ answered by LRE }
Tweet