Imagine we're working on an app that shows a user profile page. Our job is to fetch the user data, show a loading state while it's being fet

The magic of keeping one level of abstraction per function • Tymek Zapała

submited by
Style Pass
2024-11-05 23:30:13

Imagine we're working on an app that shows a user profile page. Our job is to fetch the user data, show a loading state while it's being fetched, and display whether the user is currently active. Here’s an example of what the code might look like:

This is a quite common type of code seen across React codebases. Not very complicated, rather simple stuff, with some logic sprinkled here and there. It's not pretty, but it's not particularly bad either. It has one issue though: mixed abstraction levels.

When we write code, mixing different levels of detail within a single function often leads to confusion and makes it harder to follow. For example, if something shifts to a lower level - like combining the user's first and last names into a single string - it disrupts the higher-level purpose of a function like UserProfile , which is meant to represent an entire page in our app.

Cleaner approach is to keep each function at a consistent level of abstraction. In practice, this means that high-level functions should focus on orchestration, while details should be abstracted out into smaller functions.

Leave a Comment