DEV Community

Yonatan Karp-Rudin
Yonatan Karp-Rudin

Posted on • Originally published at yonatankarp.com on

Kotlin Code Smell 8 - Too Many 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()
}
Enter fullscreen mode Exit fullscreen mode

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()
}
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)