loading...
Cover image for SLAP coding principle

SLAP coding principle

codingunicorn profile image Coding Unicorn 🦄 ・2 min read

Keep code at the single level of abstraction

In programming, there is a SLAP principle. SLAP stands for the Single Level of Abstraction Principle. What are those levels of abstraction?

  • Code at high level of abstraction: few details.
  • Code at low level of abstraction: many details.

You shall not mix mixing different levels of abstraction.

❌ In the following example, line (2) is at the higher level of abstraction than lines (3), (4) and (5):

void register() {
  throwIfEmailExists();
  if (blacklistEnabled && blacklist.contains(credentials)) {
    let hiddenPassword = passwordService.secure(credentials.password);
    throw new CannotRegisterWithBlacklistedCredentials(credentials);
  }
}

🧠 Your brain quickly understands line (1), but then begins working hard to understand lines (2), (3), and (4). If a large project is written this way, your brain will be constantly jumping between instinctive thinking (understanding the code at the high level of abstraction) and deliberate thinking (understanding code at the low level of abstraction). Your precious brain resource will be wasted and you'll get tired quickly.

✅ Now let's refactor the code so all lines are at the same level of abstraction:

void register() {
  throwIfEmailExists();
  throwIfBlacklisted();
}

In order to understand this code, your brain only needs to engage System 11 or fast, instinctive thinking. System 21 with its slower, deliberative, and logical thinking is sitting on a bench, ready to pick up more challenging tasks.

💡 Remember – always keep code at the same level of abstraction. Your brain will thank you later.

Coding Unicorn


  • 1 – System I and System II are terms from amazing book Thinking, Fast and Slow

Posted on by:

codingunicorn profile

Coding Unicorn 🦄

@codingunicorn

Hi!✌(◕‿-)✌ My name is Julia (also known as coding_unicorn on Instagram). I'm a full-stack developer specializing in Java and JavaScript.

Discussion

markdown guide
 

Great work!
Short simple and precise

 

Nice real world coding related example of System 1 and System 2 thinking 😄