Clean Code Tip: Don’t use too many method arguments

Related Articles

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

Why? How can we do that? What are the main problems with too many premiums? Take a look at the following section:

void SendPackage(
    string name, 
    string lastname, 
    string city, 
    string country,
    string packageId

If you need to use a different field on the address or person, you will need to add a new parameter and update all existing methods to match the signature of the new function.

What if we added a Country claim? Is this part of the address (Country = “Italy”) Or something related to the package (Condition = defective)?

Storing this field in the correct object helps to understand its meaning.

void SendPackage(Person person, string packageId)  

class Person  
    public string Name  get; set; 
    public string LastName  get; set; 
    public Address Address get; set;

class Address  
    public string City  get; set; 
    public string Country  get; set; 

Another reason to avoid using a lot of parameters? To avoid merger conflicts.

Suppose two developers, Alice and Bob, are working on some functionality that affects SendPackage method. Alice, in her branch, adds a new perm, bool withPriority. Meanwhile, Bob, on his branch, adds bool applyDiscount. Afterwards, both Alice and Bob merge their branches together into the main branches. What is the result? Of course, a collision: the method now has two Boolean parameters, and the order in which they are added to the end result can cause some problems. Even more so, because every call to SendPackage The method now has one (or two) new parameters, the value of which depends on the context. So, after merging, the value that Bob set for applyDiscount You can use the parameter instead of the parameter added by Alice.


In conclusion, why should we reduce the number of parameters?

  • Give context and meaning to these parameters
  • To avoid errors for location parameters
  • To avoid merger conflicts

👉 Let’s discuss it On Twitter Or in the comments section below!





Please enter your comment!
Please enter your name here

Popular Articles