DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Single Responsibility Principle: The Most Important Rule in the Software World
  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • Apache Cassandra Horizontal Scalability for Java Applications [Book]
  • Protecting Your Domain-Driven Design from Anemia

Trending

  • Detection and Mitigation of Lateral Movement in Cloud Networks
  • Docker Base Images Demystified: A Practical Guide
  • FIPS 140-3: The Security Standard That Protects Our Federal Data
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  1. DZone
  2. Data Engineering
  3. Data
  4. Levels of Abstraction

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.

By 
Domenique Tilleuil user avatar
Domenique Tilleuil
·
Oct. 19, 17 · Tutorial
Likes (28)
Comment
Save
Tweet
Share
26.4K Views

Join the DZone community and get the full member experience.

Join For Free

Writing 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

  1. Smalltalk best practice patterns by Kent Beck, ISBN 9780132852098. ↩
  2. The productive programmer by Neil Ford, ISBN 9780596519780. ↩
  3. Clean code by Robert C. Martin, ISBN 9780136083238. ↩
Abstraction (computer science) application Database Concept (generic programming) Best practice Robert C. Martin Business logic Book Data (computing)

Published at DZone with permission of Domenique Tilleuil. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Single Responsibility Principle: The Most Important Rule in the Software World
  • Improving Backend Performance Part 1/3: Lazy Loading in Vaadin Apps
  • Apache Cassandra Horizontal Scalability for Java Applications [Book]
  • Protecting Your Domain-Driven Design from Anemia

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!