Hi
Code tip: single level of abstraction
Feb 2023
A simple tip to write cleaner code
Functions should have a single level of abstraction
I discovered this tip in Uncle Bob's book Clean Code.
It is my favourite tip because it is:
- simple to reason about
- easy to apply to your work
Example
(Not a real world example - I have changed things for brevity)
/**
* Multiple levels of abstraction; we have:
* (a) function calls
* (b) property assignments
* (c) a conditional statement
*/
async function createUser(userDto: UserDto) {
const user = new User();
user.name = userDto.name;
user.email = userDto.email;
user.createdAt = Date.now();
if (userDto.country === "UK") {
logger.logActivity(`User created in the UK: ${user.id}`);
} else {
logger.logActivity(`User created somewhere in the world: ${user.id}`);
}
db.add(user);
await db.save();
}
/**
* Single level of abstraction: we only have function calls
*/
async function createUser(userDto: UserDto) {
const user = User.createFromDto(userDto);
logUserCreated(user);
createUserInDb(user);
}
This results in code that is much easier to read and maintain.
Back to top