Photo by Angel Ceballos on Unsplash
Kotlin Code Smell 002 - Functions Are Too Long
Humans get bored beyond line 10...
Play this article
TL;DR: Refactor and extract functions longer than 5-10 lines of code.
Problems
Low Cohesion
High coupling
Difficult to read
Low Reuse
Solutions
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
Â