HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpCritical

Instantiating objects with many attributes

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
instantiatingobjectswithattributesmany

Problem

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?

Solution

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

  • Replace Parameter with Method (p292)



  • Introduce Parameter Object (295)



  • Preserve Whole Object (298)



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' );


$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.

Code Snippets

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

$op = new OpenIdProvider( $params );

Context

StackExchange Code Review Q#150, answer score: 53

Revisions (0)

No revisions yet.