Yonatan Karp-Rudin
Yonatan Karp-Rudin

Follow

Yonatan Karp-Rudin

Follow
Kotlin Code Smell 002 - Functions Are Too Long

Photo by Angel Ceballos on Unsplash

Kotlin Code Smell 002 - Functions Are Too Long

Humans get bored beyond line 10...

Yonatan Karp-Rudin's photo
Yonatan Karp-Rudin
·Dec 1, 2022·

1 min read

Play this article

Table of contents

  • Problems
  • Solutions
  • Examples
  • Sample Code
  • Conclusion
  • More info
  • Credits

TL;DR: Refactor and extract functions longer than 5-10 lines of code.

Problems

  • Low Cohesion

  • High coupling

  • Difficult to read

  • Low Reuse

Solutions

  • Refactor.

  • Create small objects dealing with some tasks, and unit-test them.

  • Compose methods.

Examples

  • Libraries

Sample Code

Wrong

class ChessBoard() {
    init {
        placeOnBoard(whiteTower)
        placeOnBoard(whiteKnight)
        // All other write pieces

        // Empty space to pause definition
        placeOnBoard(blackTower)
        placeOnBoard(blackKnight)
        // All other black pieces
    }

    fun placeOnBoard(piece: Piece) = TODO()
}

Right

class ChessBoard() {
    init {
        placeWhitePieces()
        placeBlackPieces()
    }

    private fun placeWhitePieces() = TODO()
    private fun placeBlackPieces() = TODO()
}

Conclusion

Extract the long method into smaller pieces. Break complex algorithms into parts. This will also allow you to unit-test these parts more easily. Moreover, it improves readability and allows us to focus on the correct level of abstraction in your method.

More info

Credits

 
Share this