Skip to main content

Command Palette

Search for a command to run...

Code Smell 10 - Too Many Arguments

Updated
โ€ข2 min read
Code Smell 10 - Too Many Arguments
M

Iโ€™m a senior software engineer loving clean code, and declarative designs. S.O.L.I.D. and agile methodologies fan.

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.

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 marginBottom         
        ) {
    }
}

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 { }
// Class definition with methods and properties omitted for simplicity

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        
        ) {
    }
}

Detection ๐Ÿ”

Most linters warn when the arguments list is too large.

Exceptions ๐Ÿ›‘

  • Operations in real-world needing not cohesive collaborators.

Tags ๐Ÿท๏ธ

  • Bloaters

Level ๐Ÿ”‹

[X] Beginner

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.

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.