DEV Community

Cover image for Code Smell 10 - Too Many Arguments
Maxi Contieri
Maxi Contieri

Posted on • Updated on • Originally published at maximilianocontieri.com

Code Smell 10 - Too Many Arguments

Objects or Functions need too many arguments to work.

TL;DR: Don't pass more than three arguments to your functions.

Problems

  • Low maintainability

  • Low Reuse

  • Coupling

Solutions

  • Find cohesive relations among arguments

  • Create a "context".

  • Consider using a Method Object Pattern.

  • Avoid "basic" Types: strings, arrays, integers, etc. Think on objects.

Exceptions

  • Operations in real world needing not cohesive collaborators.

Sample Code

Wrong

public class Printer {   
  void print(String documentToPrint, 
         String papersize,
           String orientation, 
           boolean grayscales,
           int pagefrom,
           int pageTo,
           int copies,
           float marginLeft,
           float marginRight,
           float marginTop,
           float marginBotton         
        ){    
    }
}
Enter fullscreen mode Exit fullscreen mode

Right

final public class PaperSize {
    //...
}

final public class Document {
    //...
}

final public class PrintMargins {
    //...
}

final public class PrintRange {
    //...
}

final public class ColorConfiguration {
    //...
}

final public class PrintOrientation {
    //...
}

final public class PrintSetup {
    public PrintSetup(PaperSize papersize,
           PrintOrientation orientation, 
           ColorConfiguration color,
           PrintRange range,
           int copiesCount,
           PrintMargins margins
           ){}
}

final public class Printer {   
  void print(Document documentToPrint, 
         PrintSetup setup        
        ){    
    }
}
Enter fullscreen mode Exit fullscreen mode

Detection

Most linters warn when the arguments list is too large.

Tags

  • primitive

Conclusion

Relate arguments and group them.
Always favor real world mappings. Find in real world how to group the arguments in cohesive objects.

If a function gets too many arguments, some of them might be related to the class construction. This is a design smell too.

Relations

Credits

Photo by Tobias Tullius on Unsplash


This article is part of the CodeSmell Series.

Last update: 2021/06/13

Top comments (1)

Collapse
 
pyrsmk profile image
Aurélien Delogu • Edited

I don't really follow you on this one. I understand what you want to demonstrate but your solution is using classes as data bags. Also, having too much parameters on a method does not seem to be really the problem, since your PrintSetup class does it too. To me, the big issue here is that the language itself does not support named parameters in function calls. With this it would make the code more readable and maintainable.