Skip to main content

Command Palette

Search for a command to run...

Code Smell 03 - Functions Are Too Long

Humans get bored beyond line 10.

Published
1 min read
Code Smell 03 - Functions Are Too Long

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

Refactorings

Examples

  • Libraries

Sample Code

Wrong

<?

function setUpChessBoard() {
    $this->placeOnBoard($this->whiteTower);
    $this->placeOnBoard($this->whiteKnight);
    // A lot of lines more

    // Empty space to pause definition
    $this->placeOnBoard($this->blackTower);
    $this->placeOnBoard($this->blackKnight);
    // A lot more lines
}

Right

<?

function setUpChessBoard() {
    $this->placeWhitePieces();
    $this->placeBlackPieces();
}

Detection

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

Relations

Tags

  • Complexity

Conclusion

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

Also Known as

  • Long Method

More info

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.

Code Smells

Part 1 of 50

In this series, we will see several symptoms and situations that make us doubt the quality of our developments. We will present possible solutions. Most are just clues. They are no hard rules.