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

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

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

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

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

Related

  • Python Techniques for Text Extraction From Images
  • OneStream Fast Data Extracts APIs
  • Reversing an Array: An Exploration of Array Manipulation
  • Setup ActiveMQ Artemis on Windows

Trending

  • Recurrent Workflows With Cloud Native Dapr Jobs
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Streamlining Event Data in Event-Driven Ansible
  • Mastering Fluent Bit: Installing and Configuring Fluent Bit on Kubernetes (Part 3)

Method Length and Extract 'Til You Drop

If your methods are longer than five lines of code, it's a sign that you should start to extract. And once you start, extract till you drop!

By 
Grzegorz Ziemoński user avatar
Grzegorz Ziemoński
·
Apr. 28, 17 · Tutorial
Likes (28)
Comment
Save
Tweet
Share
12.9K Views

Join the DZone community and get the full member experience.

Join For Free

As a typical nerd (and a DZone Zone Leader), I tend to read a lot of blog posts and comments about programming. One thing that keeps amazing me is how long people’s functions tend to be and how many people are convinced this is the right way to code. In reality, a readable function should rarely exceed five lines of code.

Take a short look at this function:

public void show() {
    Week week = visitCalendar.getCurrentWeek();
    System.out.println(week.getStart() + " - " + week.getEnd());

    for (DayOfWeek day : VisitCalendar.OPEN_DAYS) {
        System.out.println(day + ":");
        List<Visit> visitsOnDay = visitCalendar.visitsOn(day);
        if (visitsOnDay.isEmpty()) {
            System.out.println("No visits!");
        } else {
            for (Visit visit : visitsOnDay) {
                System.out.println(visit.getTime() + ": " + visit.getOwnerName());
                System.out.println("Pets: " + visit.getPetNames());
            }
        }
    }

    try (Scanner scanner = new Scanner(System.in)) {
        String command;
        do {
            command = scanner.nextLine();
        } while (!controller.execute(command));
    }
}


How readable is that piece of code? Are you able to tell what it does just by taking a quick look at it? Two little extractions should make things clearer:

public void show() {
    Week week = visitCalendar.getCurrentWeek();
    System.out.println(week.getStart() + " - " + week.getEnd());

    for (DayOfWeek day : VisitCalendar.OPEN_DAYS) {
        System.out.println(day + ":");
        show(visitCalendar.visitsOn(day));
    }

    askForCommand();
}

private void show(List<Visit> visitsOnDay) {
    if (visitsOnDay.isEmpty()) {
        System.out.println("No visits!");
    } else {
        for (Visit visit : visitsOnDay) {
            System.out.println(visit.getTime() + ": " + visit.getOwnerName());
            System.out.println("Pets: " + visit.getPetNames());
        }
    }
}

private void askForCommand() {
    try (Scanner scanner = new Scanner(System.in)) {
        String command;
        do {
            command = scanner.nextLine();
        } while (!controller.execute(command));
    }
}


Much better. Now, the three functions are fairly readable and it should be easier to reason about what’s happening in there. But that’s still not good enough. Our show() method has mixed levels of abstraction and there’s still a loop inside an if statement. To deal with the first problem, we can simply extract two methods:

public void show() {
    show(visitCalendar.getCurrentWeek());

    for (DayOfWeek day : VisitCalendar.OPEN_DAYS) {
        show(day);
        show(visitCalendar.visitsOn(day));
    }

    askForCommand();
}

private void show(Week week) {
    System.out.println(week.getStart() + " - " + week.getEnd());
}

private void show(DayOfWeek day) {
    System.out.println(day + ":");
}


Now, how readable is that? It’s trivial, but that’s a good thing. We want our code to be trivial. Now to the second problem. Guess what we’ll do. That’s right, extract again!

private void show(List<Visit> visitsOnDay) {
    if (visitsOnDay.isEmpty()) {
        showNoVisits();
    } else {
        visitsOnDay.forEach(this::show);
    }
}

private void showNoVisits() {
    System.out.println("No visits!");
}

private void show(Visit visit) {
    System.out.println(visit.getTime() + ": " + visit.getOwnerName());
    System.out.println("Pets: " + visit.getPetNames());
}


Do you see how much clearer the code becomes? That’s exactly the point. When you extract, things become more digestible and it’s easier to preserve proper levels of abstraction. The fun part of it? You can extract all the time! Extract till you drop!

And in the meantime, your functions will become smaller and smaller. Usually less than six lines of code long. This is approximately the size at which code becomes pleasantly trivial. Therefore, beware of functions longer than that and continuously seek possibilities to extract further. The readers of your code will thank you.

Extract

Published at DZone with permission of Grzegorz Ziemoński, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Python Techniques for Text Extraction From Images
  • OneStream Fast Data Extracts APIs
  • Reversing an Array: An Exploration of Array Manipulation
  • Setup ActiveMQ Artemis on Windows

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!