Mostafa Abedi
Mostafa Abedi

Reputation: 541

Many method argument vs a bulk argument

In terms of efficiency which one is better :

  1. Method with many arguments
  2. A bulk argument that contains all of mentioned arguments

I mean :

public function addToDb($firstName, $lastName, $phone, $address, ...)
{

Or

public function addToDb(Request $request)
{
  $firstName = $request->firstName;
  $lastName= $request->lastName;
  $phone= $request->phone;
  $address= $request->address;
  //

Please keep in mind that in this example $request class maybe has many useless arguments and methods.

Upvotes: 5

Views: 146

Answers (2)

Davit Zeynalyan
Davit Zeynalyan

Reputation: 8618

The second method is more priority. For example you define

function addToDb($firstName, $lastName, $phone, $address){...}

And used this methods for example 10 times. If in the future your app need some changes and you must be change some parameter for example $firstName, $lastName, must be change to name, that case you must be change your initial function to

function addToDb($name, $phone, $address){...}

And int 10 times where called this methods you also must be change. But in seconds Case you must be change only body of function like this

public function addToDb(Request $request)
{
  $name = $request->firstName . '' . $request->lastName; 

Also you can use 3-rd structure

function someFunction(...) {
    $parameterWithData = [
        'firstName' => 'firt name',
        'lastName' => 'last name'
        .....
    ];
    $this->test($parameterWithData);
}


function test($parameterWithData)
{
    extract($parameterWithData);
    dd($firstName, $lastName); // must be print `first_name, last name`
}

in extract function all keys you can use as variable http://php.net/manual/en/function.extract.php

Upvotes: 5

piotrq
piotrq

Reputation: 96

The main rule is "The ideal number of arguments for a function is zero". Of course it hard to do that but we should keep code simply and better is the second solutions, especially when you use Data Value Object

Upvotes: 4

Related Questions