Kotlin Code Smell 8 - Too Many Arguments
Yonatan Karp-Rudin
Posted on December 11, 2022
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.
Stay updated with my latest thoughts and ideas by registering for my newsletter. Connect with me on LinkedIn or Twitter. Let's stay connected and keep the conversation going!
More Info
Credits
Posted on December 11, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.