Code Smell 03 - Functions Are Too Long

Maxi Contieri - Oct 22 '20 - - Dev Community

Humans get bored beyond line 10.

TL;DR: Refactor and extract functions longer than 5 lines.

Problems

  • Low Cohesion
  • High coupling
  • Difficult to read
  • Low Reuse

Solutions

1) Refactor

2) Create small objects dealing with some tasks. Unit test them.

3) Compose methods

Examples

  • Libraries

Sample Code

Wrong

<?

function setUpChessBoard() {

    $this->placeOnBoard($this->whiteTower);
    $this->placeOnBoard($this->whiteKnight);
    //A lot of lines
    //.....
    $this->placeOnBoard($this->blackTower);
}
Enter fullscreen mode Exit fullscreen mode

Right

<?

function setUpChessBoard() {
    $this->placeWhitePieces();
    $this->placeBlackPieces();
}
Enter fullscreen mode Exit fullscreen mode

Detection

All linters can measure and warn when methods are larger than a predefined threshold.

Relations

Also Known as

  • Long Method

More info

Tags

  • Complexity

Conclusion

Extract long method into smaller pieces. Break complex algorithms in parts. You can also unit test these parts.

Credits

Photo by Hari Panicker on Unsplash


Programs are meant to be read by humans and only incidentally for computers to execute.

Donald Knuth


This article is part of the CodeSmell Series.

Last update: 2021/06/01

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player