Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 928
Mostafa Abedi Avatar asked Dec 12 '18 10:12

Mostafa Abedi


2 Answers

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

like image 150
Davit Zeynalyan Avatar answered Sep 21 '22 18:09

Davit Zeynalyan


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

like image 40
piotrq Avatar answered Sep 22 '22 18:09

piotrq