Kotlin Code Smell 8 - Too Many Arguments
Optimizing Function Design: The Art of Grouping and Simplifying Arguments
TL;DR: Avoid passing more than three arguments to your functions.
Problems
Low maintainability.
Low reusability.
Coupling.
Readability.
Solutions
Identify cohesive relationships among arguments.
Create a "context" or related group.
Consider using the Method Object Pattern.
Avoid using "basic" types such as strings, arrays, and integers, and instead think in terms of objects.
Exceptions
- Operations in the real world that do not require cohesive collaborators.
Sample Code
Wrong
class Printer {
fun print(
documentToPrint: String,
paperSize: String,
orientation: String,
grayScales: Boolean,
pageFrom: Int,
pageTo: Int,
copies: Int,
marginLeft: Float,
marginRight: Float,
marginTop: Float,
marginBottom: Float
): Unit = TODO()
}
Right
class PaperSize {
//...
}
class Document {
//...
}
class PrintMargins {
//...
}
class PrintRange {
//...
}
class ColorConfiguration {
//...
}
class PrintOrientation {
//...
}
class PrintSetup(
paperSize: PaperSize,
orientation: PrintOrientation,
color: ColorConfiguration,
range: PrintRange,
copiesCount: Int,
margins: PrintMargins
)
class Printer {
fun print(
documentToPrint: Document,
setup: PrintSetup
): Unit = TODO()
}
Conclusion
To improve code quality, identify and group related arguments. Aim for real-world mappings and cohesive objects.
If a function requires too many arguments, some of them might be better suited for class construction. This is also a design issue.