Single Level of Abstraction
SLAP · principio SLA
Escrito por Darjus Kazakevic · revisado el
A function should read like a summary of what it does.
The Single Level of Abstraction Principle (SLAP) is about how a function reads. If validateCart(cart) sits next to db.query("INSERT INTO orders …"), the function mixes a business step with raw plumbing. The reader has to switch between the two on every line.
The function's name sets the level. checkout() should read like checkout: reserve stock, charge the card, record the sale, send a receipt. The SQL, retries and hashing go one level down, into helpers named for what they do.
En esencia — Keep every line of a function at one level of detail, and move the SQL, loops and string building into helpers named for what they do.
Cuándo recurrir a él
Recurre a él cuando
- A function long enough that you skim it to understand it
- Use-case functions that coordinate several steps
- While refactoring: extract until each function reads at one level
Reconsidéralo cuando
- Low-level functions whose whole job is the detail, like a parser loop
- Tiny functions that are already at one level
- When a helper needs so many parameters that inline code is clearer
The idea, in parts
- Level of abstraction
- How far a statement is from the machine. "Notify the customer" is high level. Building a MIME message and opening an SMTP connection is low level.
- Mixed levels
- A line of clear intent, then a line of dense plumbing, then intent again. You cannot skim the function to learn what it does, because half the lines are about how.
- Extract to go one level down (Composed Method)
- Move each low-level block into a helper named for its intent. The caller reads at its own level again, and the helper follows the same rule one level down.
- The name sets the level
- A function's name promises a level of detail. If the body keeps dropping below that level, either extract the low-level lines or rename the function.
Reglas de diseño
- Extract each low-level block into a named helper
- When a group of lines does one technical job, move it into a function named for its intent: chargeCard(), not postWithSignature(). The caller then reads at one level again.
- Let the function name set the level
- checkout() promises business steps, so every line should be one. If a line drops into SQL or string building, extract it, or rename the function to match what it really does.
- Stop extracting when it stops helping
- A helper is worth it when its name says more than its body. Ten one-line functions with vague names are harder to follow than the code they replaced.
Errores habituales
- Vague helper names (doStuff, process2) that hide the work instead of naming it.
- Splitting so far that reading one feature means opening ten one-line functions.
- One stray SQL line left in an otherwise high-level function.
- Thinking "one level" means "short". A long function can still be at one level.