Levels of Abstraction
This refresher of the various levels of abstraction in your code contains some recommended best practices and advice for tackling code smells.
Join the DZone community and get the full member experience.
Join For FreeWriting code is all about abstractions. They help us grasp the complexity of the code by hiding low-level details from high-level concepts. The key to readable code lies in grouping the right level of abstraction in the same unit of code.
Kent Beck originally came up with the following guidelines in his book Smalltalk best practice patterns:
Divide your program into methods that perform one identifiable task. Keep all of the operations in a method at the same level of abstraction. This will naturally result in programs with many small methods, each a few lines long.
Later on, this concept got coined by Neil Ford as SLAP: Single Level of Abstraction Principle in his excellent book The Productive Programmer, after which Robert C. Martin restated the principle in his Clean Code book:
Mixing levels of abstraction within a function is always confusing. Readers may not be able to tell whether a particular expression is an essential concept or a detail. Worse, like broken windows, once details are mixed with essential concepts, more and more details tend to accrete within the function.
Kent Beck originally proposed the concept of composed methods. A composed method consists of multiple calls to other private methods, each having a clear name to identify it’s responsibility. This technique results on smaller methods having only one level of abstraction and, by consequence, only one responsibility. The following code sample illustrates what this would look like.
public class CoffeeMaker {
public void makeCoffee() {
grindBeans();
boilWater();
pourWater();
}
private void grindBeans() {
// ...
}
private void boilWater() {
// ...
}
private void pourWater() {
// ...
}
}
As you can see, there are at least two levels of abstraction in this code. The makeCoffee()
method exhibits a higher level of abstraction than the other methods. It acts as an orchestration layer, enforcing policy on the other methods.
Code Smells
Loop Bodies
Often the body of a loop can be extracted, resulting in a separate private method. Loops should ideally contain a single statement (usually a method call). Sometimes, this is not achievable without other drawbacks but large loop bodies can certainly be considered a smell.
public class CarDtoFactory {
public List < CarDto > create(List < Car > cars) {
return cars.stream()
.map(car - > {
CarDto carDto = new CarDto();
carDto.setHorsePower(car.calculateHorsePower());
return carDto;
})
.collect(Collectors.toList());
}
private class Car {
int calculateHorsePower() {
return 200;
}
}
private class CarDto {
int horsePower;
void setHorsePower(int hp) {
this.horsePower = hp;
}
}
}
The example above is a factory responsible for converting our Car
entity to a data transfer object. Look carefully at the create()
method. First, there is the loop that acts on the whole result set. Secondly, there is the loop body that converts a single Car
Entity to a CarDto
. The body of the loop could easily be extracted, avoiding mixing the level of abstraction.
Abstractions and Layering
Of course, methods are not the only place where abstractions are at play. Layers inside our application should also adhere to the same level of abstraction across the application. In a typically layered application, we are supposed to find specific levels of abstraction in each of the layers, meaning that when you look at the application from the boundaries inwards, our code should get more specific when passing through each layer. Failing to do so results in code that is hard to read.
The Application Layer
A typically layered application consists of an application layer or a service layer, which acts as a facade in front of the domain model. This layer contains use cases or command handlers. It contains high-level policy that can be understood by a business stakeholder by looking at the name of the class and its content. This layer should not contain any business logic. It merely orchestrates the domain layer. As a result, the code should be concise and easy to read.
The Domain Layer
The domain layer is a lower level of abstraction. It contains detailed business logic that is accessed from the application layer. The code in this layer will be a lot more complex than the application layer. If you want more details about specific business rules, how they relate to domain entities or aggregates, then this is the right place to look. The domain layer will typically have different levels of abstractions on its own. Aggregate root entities exhibit a higher level of abstraction then entities.
The Infrastructure Layer
The infrastructure layer consists of the lowest level of abstraction, as it deals with the nitty-gritty details such as database persistence, networking protocols, and other details needed by the domain layer to persist data or communicate with other systems.
Footnotes
Published at DZone with permission of Domenique Tilleuil. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments