Jump to content

When passing parameters, do I pass only what I need or do I pass entire parent object?


dennis-fedco

Recommended Posts

I work with a large codebase and I have this situation come up fairly often:

 

the legacy class has large objects such as:

$design->motor->dimensions->a;
$design->motor->dimensions->bd;
$design->specifications->weight;
$design->data->height;
//etc

When I create a new class, that class sometimes operates on the specific data, so say:

class MyClass
{
    public function compute($weight, $height, $a)
    {
        //stuff
    }
}

//and I call this for example as such:
(new MyClass())->compute($design->specifications->weight, $design->data->height, $design->motor->dimensions->a);

CONS:  Potential issue:  if design specs change and I need to change things parameters in "compute" function, I need to "re-key" the variables I pass to the function, and adjust things accordinly in MyClass as wel.

PROS:  only the exact data is being passed, and this data can come from anywhere it is viable, so in effect the function is fairly well separated, I think.

 

Alternative option for me is to pass the entire design object, i.e

class MyClass
{
    public function compute(&$design) //can also be done via DI through a setter or constructor.
    {
         print $design->specifications->weight;
         print ($design->data->height + $design->motor->dimensions->a);
        //stuff
    }
}

(new MyClass())->compute($design);

PROS:  In this case when things change internally in which variables are needed and how things are computed, I only need to change the code in compute function of the class itself.

CONS:  MyClass now needs to be aware of how $design object is constructed.

 

When it comes to this parameter passing, and Dependency Injection like this in general, does Computer Science advocate a preference on this issue?  Do I pass the entire object, or do I pass only the bits and pieces I need?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.