Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coding standards: Large amount of arguments

Tags:

oop

php

Hey, I'm a fresh out of college graduate. I'm working on a project that I expect will be ultimately maintained by somebody else. I keep encountering an annoying situation on this project, and that is objects that require many private variables and as a result very long constructors.

Apart from variable naming, there isn't any coding standard enforced. I'm wondering how to deal with the likes of this. Sometimes I fear I will see some of my own code on dailywtf in the future!

I tought about trying to enclose some of these arguements in other classes, but in this situation it doesnt really make sense.

Is this a total non-issue or is it something that should and is easily correctable?

public function __construct($uCode = '', $uName = '', $uTime = '', $uArea = '', $uDomain = '', $uText = '', $uId = '', $uNum = '', $uVideo = 0, $uAudio = 0, $uImage = 0){
like image 329
user110310 Avatar asked May 28 '09 23:05

user110310


People also ask

How many arguments is too many for a function?

Functions with three arguments (triadic function) should be avoided if possible. More than three arguments (polyadic function) are only for very specific cases and then shouldn't be used anyway.

How do you fix too many arguments in a function?

So to fix the error “You've entered too many arguments for this function” you need to go through the content of the cell, character-by-character, to ensure that there are no syntax errors. In other words, you need to check whether all opened brackets are closed and all commas are properly in place.

How many arguments can a method call have?

Except for functions with variable-length argument lists, the number of arguments in a function call must be the same as the number of parameters in the function definition. This number can be zero. The maximum number of arguments (and corresponding parameters) is 253 for a single function.

Can a function have too many arguments?

Many times, we tend to add too many parameters to a function. But that's not the best idea: on the contrary, when a function requires too many arguments, grouping them into coherent objects helps writing simpler code.


1 Answers

Generally speaking, if you have more than about 4 arguments, you are better off using a temporary object or array instead. Often many of the parameters because optional and this can get pretty awkward and error prone pretty fast. So:

class MyClass {
  public function __construct($options) { ... }
...
}

$o = new MyClass(array(
  'uCode' => 'some value',
  'uText' => 'another value',
));

Compare that to:

$o = new MyClass('some value', '', '', '', '', 'another value');

Notice how the array version only includes what you want to pass.

like image 109
cletus Avatar answered Oct 22 '22 16:10

cletus