Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it better to create methods with a long list of parameters or wrap the parameters into an object?

Tags:

c#

refactoring

Is it better(what is the best practice) to create methods with a long list of parameters or wrap the parameters into an object?

I mean lets say i have a Client data type with a long list of properties and i want to update all the properties at once. is it better to do something like

public int Update(int id, string name, string surname, string streetAddress, string streetAddress2, string postcode, string town, string city, string nationality, string age, string gender,string job)
{  }

or wrap all the properties in a object and do something like

public int Update(Client client)
{  }

thanks

like image 588
GigaPr Avatar asked Apr 08 '10 09:04

GigaPr


People also ask

How do you deal with a long parameter list?

Long parameter list can be caused by too complex methods. Another reason is avoiding dependencies. One way to reduce number of parameters is to replace a parameter with a method call. You can also preserve a whole object or introduce a parameter object.

How do you avoid too many parameters in a function?

There are two techniques that can be used to reduce a functions' arguments. One of them is to refactor the function, making it smaller, consequently, reducing the arguments' number. The Extract Method technique can be use to achieve this goal.


1 Answers

In his book Refactoring, Martin Fowler explicitly calls out long parameter lists as a code smell and suggest refactoring such methods to use a Parameter Object.

A variation is to identify how those many parameters group themselves, and create more than one Parameter Object that represent each such group.

The advantage of a Parameter Object is that the code becomes more readable when you can give the Parameter Object a communicative name. It may turn out that the Parameter Object represents a real Domain Concept, and the next thing you can do is to start moving behavior into it.

like image 107
Mark Seemann Avatar answered Oct 16 '22 18:10

Mark Seemann