Knowledgebase

Writing Readable Functions Print

  • softwareengineering, software, troubleshooting, guide, howto, solution, zillionkinghost, hosting
  • 0

Small units with one purpose.

WHAT A FUNCTION SHOULD DO

One thing, at one level of abstraction.

WHAT ONE LEVEL MEANS

Not mixing high-level orchestration with low-level detail in the same function.

WHAT LENGTH SUGGESTS A PROBLEM

Anything that does not fit on a screen, usually.

WHY

It becomes difficult to hold in mind.

WHAT TO DO ABOUT A LONG FUNCTION

Extract the parts that have a name.

WHY THAT TEST

If a block can be named, it is a separate responsibility.

WHAT TO LIMIT

Parameters. Many parameters indicate too many responsibilities.

WHAT TO AVOID

Boolean parameters changing behaviour Output parameters Functions that return a value and also change state, without saying so

WHAT TO PREFER

Early returns for exceptional cases.

WHAT THAT ACHIEVES

The main path at one level of indentation.

WHAT NESTING DEPTH SUGGESTS

Beyond two or three levels, something should be extracted.

WHAT TO MAKE EXPLICIT

What the function requires, and what it guarantees.

WHAT TO AVOID ENTIRELY

Functions that modify global state invisibly.


Was this answer helpful?
Back

Are you happy with your experience? Leave us a review on Trustpilot.


Trustpilot