Single Level of Abstraction Principle
What is the Single Level of Abstraction (SLA) principle, why is it important, and how to apply it?
There are many well-known principles in software development, such as SOLID or Don’t Repeat Yourself. Such principles offer useful guidance for creating future-proof, human-readable, good-quality software.
Here at Outfunnel, we’ve found that applying the Single Level of Abstraction (SLA) principle has contributed a lot to our code quality. It’s a principle that is quite easy to apply and it offers the benefit of making the code much easier to read and digest.
This article takes a look at the Single Level of Abstraction principle, how to apply it, and where its limits are.
What is the Single Level of Abstraction Principle?
The idea goes back to Kent Beck’s Composed Method pattern in Smalltalk Best Practice Patterns and was popularized by Uncle Bob in his book Clean Code.
The core logic of the principle is simple: when we write a function, the statements in that function need to be at the same level of abstraction.
Why do we need such a principle, after all? SLA aims to increase the readability of a function. If a function includes statements that are at different levels of abstraction, we need to jump through mental hoops in order to grasp the main point of the function.
How to Recognize the Level of a Statement
Abstraction levels aren’t labelled in the code, so we need a way to spot them. A few questions help:
- What or how? A statement at a high level says what happens:
getContacts(). A statement at a low level says how it happens:axios.get(url),response.data.results,statusCode === 429. A function should answer one of those questions, not both. - Would it need a comment? If we feel the urge to write
// fetch the contactsabove a few lines, those lines are a function with a name waiting to be extracted. - Whose vocabulary is it? Words from the business domain (contacts, properties, normalize) and words from the infrastructure (HTTP, status code, response body, retry) rarely belong in the same function.
The first question is the one we use most. Reading a function aloud and hearing it switch between what and how halfway through is usually enough to notice a violation.
The SLA Principle in Action
Let’s see a specific example of how the SLA principle proves useful.
Imagine we have a function that needs to fetch both the properties and the contacts from the HubSpot CRM:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
const axios = require('axios');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const HUBSPOT_API_PROPERTIES_PATH = 'https://api.hubapi.com/crm/v3/properties/contacts';
const HUBSPOT_API_CONTACTS_PATH = 'https://api.hubapi.com/crm/v3/objects/contacts';
async function getProperties() {
try {
const response = await axios.get(HUBSPOT_API_PROPERTIES_PATH);
return response.data.results;
} catch (err) {
const statusCode = err.response.status;
if (statusCode === 500) {
return getProperties();
} else if (statusCode === 429) {
await sleep(10000);
return getProperties();
} else {
throw err;
}
}
}
async function getNormalizedContacts() {
const properties = await getProperties();
const response = await axios.get(HUBSPOT_API_CONTACTS_PATH);
const contacts = response.data.results;
return normalizeContacts({contacts, properties});
}
In this example, the function getNormalizedContacts violates the SLA principle. How? The function can mentally be split into three different parts: the first part retrieves the contact properties, the second part retrieves the contacts, and the third part normalizes the responses.
On one hand, getting the properties is nicely separated into a function. On the other hand, obtaining the contacts is not abstracted away at all. Clearly, the second part of the function is at a lower abstraction level than the first one, because it involves making an HTTP request and parsing the response.
The first step of fixing getNormalizedContacts is relatively straightforward - we should just make fetching the contacts a separate function. Doing so means that the function is now nice and tidy - all it cares about is fetching both the properties and contacts and normalizing the responses. All this without knowing the exact details.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
const axios = require('axios');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const HUBSPOT_API_PROPERTIES_PATH = 'https://api.hubapi.com/crm/v3/properties/contacts';
const HUBSPOT_API_CONTACTS_PATH = 'https://api.hubapi.com/crm/v3/objects/contacts';
async function getProperties() {
try {
const response = await axios.get(HUBSPOT_API_PROPERTIES_PATH);
return response.data.results;
} catch (err) {
const statusCode = err.response.status;
if (statusCode === 500) {
return getProperties();
} else if (statusCode === 429) {
await sleep(10000);
return getProperties();
} else {
throw err;
}
}
}
async function getContacts() {
try {
const response = await axios.get(HUBSPOT_API_CONTACTS_PATH);
return response.data.results;
} catch (err) {
const statusCode = err.response.status;
if (statusCode === 500) {
return getContacts();
} else if (statusCode === 429) {
await sleep(10000);
return getContacts();
} else {
throw err;
}
}
}
async function getNormalizedContacts() {
const properties = await getProperties();
const contacts = await getContacts();
return normalizeContacts({contacts, properties});
}
However, both getProperties and getContacts now violate the SLA principle. The functions consist of making a request over the network, parsing the response, and handling the errors.
Once again, fixing both functions is straightforward - we move the request and its retry logic into one function and the parsing of the response into another. getProperties and getContacts are left with two statements each, both at the same level:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const axios = require('axios');
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
const HUBSPOT_API_PROPERTIES_PATH = 'https://api.hubapi.com/crm/v3/properties/contacts';
const HUBSPOT_API_CONTACTS_PATH = 'https://api.hubapi.com/crm/v3/objects/contacts';
const MAX_ATTEMPTS = 3;
const isRetryable = err => {
const statusCode = err.response && err.response.status;
return statusCode === 500 || statusCode === 429;
};
const retryDelay = err => err.response.status === 429 ? 10000 : 0;
async function getWithRetry(url, attempt = 1) {
try {
return await axios.get(url);
} catch (err) {
if (!isRetryable(err) || attempt >= MAX_ATTEMPTS) {
throw err;
}
await sleep(retryDelay(err));
return getWithRetry(url, attempt + 1);
}
}
const parseResponse = response => response.data.results;
async function getProperties() {
const response = await getWithRetry(HUBSPOT_API_PROPERTIES_PATH);
return parseResponse(response);
}
async function getContacts() {
const response = await getWithRetry(HUBSPOT_API_CONTACTS_PATH);
return parseResponse(response);
}
async function getNormalizedContacts() {
const properties = await getProperties();
const contacts = await getContacts();
return normalizeContacts({contacts, properties});
}
Finally, the request and its retries live in getWithRetry, the knowledge of HubSpot’s response shape lives in parseResponse, and getProperties and getContacts no longer need a try/catch at all. As a bonus, the retry logic exists once instead of twice, and it now gives up after a few attempts instead of looping forever.
Comparing the first and the last version of the code, we can see a great improvement in readability. Here is the first version again:
1
2
3
4
5
6
7
8
9
async function getNormalizedContacts() {
const properties = await getProperties();
const response = await axios.get(HUBSPOT_API_CONTACTS_PATH);
const contacts = response.data.results;
return normalizeContacts({contacts, properties});
}
If somebody happened to read the first version, it would take them quite a lot of effort to grasp the main goal of the function. Now, it’s significantly easier with the final version:
1
2
3
4
5
6
async function getNormalizedContacts() {
const properties = await getProperties();
const contacts = await getContacts();
return normalizeContacts({contacts, properties});
}
Taking It Too Far
SLA tells us when to extract a function. It doesn’t tell us when to stop, and it’s possible to overdo it. Here is the final getNormalizedContacts after one refactoring round too many:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
async function getNormalizedContacts() {
const data = await fetchData();
return normalize(data);
}
async function fetchData() {
const properties = await getProperties();
const contacts = await getContacts();
return {contacts, properties};
}
function normalize(data) {
return normalizeContacts(data);
}
Every function is now at a single level of abstraction, and the code is worse. To learn what getNormalizedContacts does, we have to hop through three functions, two of which add nothing: fetchData is a name that says less than the two lines it hides, and normalize just renames normalizeContacts.
The test we use is simple: a function earns its existence when its name tells the reader something the body would have made them work out. getContacts passes, because the reader no longer needs to know about URLs, retries, or response shapes. fetchData fails, because the reader still has to open it to find out which data.
By the same test, parseResponse is borderline. It’s a one-liner, but it hides the fact that HubSpot wraps the results in data.results. If the API returned the array directly, we’d inline it.
Conclusion
Creating future-proof and readable software requires us to follow certain principles. The Single Level of Abstraction (SLA) principle is one that helps us achieve that goal. The point of SLA is to ensure that all statements in a function are at the same level of abstraction. Like every principle, it has a limit: we extract a function when its name hides a detail the caller doesn’t need, not merely to make functions shorter.
By applying it at Outfunnel on a daily basis over the long term, we’ve managed to increase readability and decrease the number of code comments required.