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
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
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
Partner Zones AWS Cloud
by AWS Developer Relations
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
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. The Stepdown Rule

The Stepdown Rule

Ever wondered how to organize your methods inside a class? Or maybe you left it to common sense and random gut feelings. Worry not, here comes the stepdown rule!

Grzegorz Ziemoński user avatar by
Grzegorz Ziemoński
·
Mar. 28, 17 · Tutorial
Like (16)
Save
Tweet
Share
48.24K Views

Join the DZone community and get the full member experience.

Join For Free

It has recently occurred to me that some people are ordering the functions in a class randomly, mostly based on gut feelings. It’s a good indicator that we should rehash the old, simple but very important…

Stepdown Rule

The rule tells us that the code in our class should be readable from top to bottom, descending one level of abstraction per function. It implies that the function ordering is no longer random. A caller function should always reside above the callee function.

Bad: Wrong Order

private void serve() {
    wife.give(fryingPan.getContents(20, PERCENT));
    self.give(fryingPan.getContents(80, PERCENT)); // huehuehue
}

private void addEggs() {
    fridge
        .getEggs()
        .forEach(egg -> fryingPan.add(egg.open());
}

private void cook() {
    fryingPan.mixContents();
    fryingPan.add(salt.getABit());
    fryingPan.mixContents();
}

public void makeBreakfast() {
   addEggs();
   cook();
   serve();
}


As you can see, organizing the code randomly makes it far harder to comprehend. Also, you might not be interested in comprehending the details at all — you could just want to get the idea on how the breakfast is done and the bad organization just caused you to read a lot of stuff that you didn’t want to.

Bad: Mixed Levels of Abstraction

public void makeBreakfast() {
   addEggs();
   cook();
   wife.give(fryingPan.getContents(20, PERCENT));
   self.give(fryingPan.getContents(80, PERCENT)); // huehuehue
}

private void addEggs() {
    fridge
        .getEggs()
        .forEach(egg -> fryingPan.add(egg.open());
}

private void cook() {
    fryingPan.mixContents();
    fryingPan.add(salt.getABit());
    fryingPan.mixContents();
}


It’s also important to extract the methods so that they keep the same level of abstraction. Even if the makeBreakfast method is not too long at this point, it’s still relatively hard to read.

To make a breakfast, you need to:

  • Add eggs
  • Cook them
  • Give your wife 20 percent of frying pan contents
  • Give yourself 80 percent of frying pan contents

Doesn’t that sound ridiculous?

Good

public void makeBreakfast() {
   addEggs();
   cook();
   serve();
}

private void addEggs() {
    fridge
        .getEggs()
        .forEach(egg -> fryingPan.add(egg.open());
}

private void cook() {
    fryingPan.mixContents();
    fryingPan.add(salt.getABit());
    fryingPan.mixContents();
}

private void serve() {
    wife.give(fryingPan.getContents(20, PERCENT));
    self.give(fryingPan.getContents(80, PERCENT)); // huehuehue
}


Top-to-bottom, the same level of abstraction per function, one level of abstraction down per function call – as simple as that!

What If…

  • … the lower-level function is used by two or more higher-level functions? Then place it below the last usage.
    public void makeBreakfast() {
        addEggs();
        cook();
        serve();
    }
    
    // addEggs(), cook()
    
    public void makeDinner() {
        // stuff
        serve();
    }
    
    private void serve() {
        wife.give(fryingPan.getContents(20, PERCENT));
        self.give(fryingPan.getContents(80, PERCENT)); // huehuehue
    }
  • … there are two similar functions in the class? That’s actually a common temptation. As programmers, we’re organized minds. We like symmetry and all that stuff. Wouldn’t it look good if we did something like this:
    public void makeBreakfast() {
        addEggs();
        cook();
        serveBreakfast();
    }
    
    // addEggs(), cook()
    
    public void makeDinner() {
        // stuff
        serveDinner();
    }
    
    private void serveBreakfast() {
        wife.give(fryingPan.getContents(20, PERCENT));
        self.give(fryingPan.getContents(80, PERCENT)); // huehuehue
    }
    
    private void serveDinner() {
        wife.give(pot.getContents(40, PERCENT));
        self.give(pot.getContents(60, PERCENT)); // still!
    }

    No. People rarely read or search the code by method similarity. Stay top-to-bottom:
    public void makeBreakfast() {
        addEggs();
        cook();
        serveBreakfast();
    }
    
    // addEggs(), cook()
    
    private void serveBreakfast() {
        wife.give(fryingPan.getContents(20, PERCENT));
        self.give(fryingPan.getContents(80, PERCENT)); // huehuehue
    }
    
    public void makeDinner() {
        // stuff
        serveDinner();
    }
    
    private void serveDinner() {
        wife.give(pot.getContents(40, PERCENT));
        self.give(pot.getContents(60, PERCENT)); // still!
    }
  • … I’m writing a test, not a production class? Yet another common temptation. We often have some “factory” methods to prepare our test data and they might not be necessary to comprehend the test itself:
    @Test
    public void breakfastShareMakesHappiableWifeHappy() {
        Wife wife = happiableWife();
        Husband husband = new TypicalMan(wife);
    
        husband.makeBreakfast();
    
        assertTrue(wife.isHappy());
    }
    
    @Test
    public void dinnerShareMakesAngryWifeLessAngry() {
        Wife wife = angryWife();
        Husband husband = new TypicalMan(wife);
        Long initialAnger = wife.getAnger();
    
        husband.makeDinner();
    
        assertTrue(initialAnger > wife.getAnger());
    }
    
    private Wife happiableWife() {
        Wife wife = new Wife();
        wife.set... // complicated stuff
        wife.set...
        wife.set...
        ...
        return wife;
    }
    
    private Wife angryWife() {
        Wife wife = new Wife();
        wife.tellStupidJoke(); // far easier!
        return wife;
    }

    This one’s tricky, but I’d stick to the stepdown (top-to-bottom) approach. I believe that in a majority of cases, we feel tempted to push such stuff to the bottom because we’re too lazy to make the code right. If the test setup takes too much work and makes the test incomprehensible, maybe it means that we should improve the design or use some patterns, instead of “put it down and forget?”
    @Test
    public void breakfastShareMakesHappiableWifeHappy() {
        Wife wife = happiableWife();
        Husband husband = new TypicalMan(wife);
    
        husband.makeBreakfast();
    
        assertTrue(wife.isHappy());
    }
    
    private Wife happiableWife() {
        Wife wife = new Wife();
        wife.set... // complicated stuff
        wife.set...
        wife.set...
        ...
        return wife;
    }
    
    @Test
    public void dinnerShareMakesAngryWifeLessAngry() {
        Wife wife = angryWife();
        Husband husband = new TypicalMan(wife);
        Long initialAnger = wife.getAnger();
    
        husband.makeDinner();
    
        assertTrue(initialAnger > wife.getAnger());
    }
    
    private Wife angryWife() {
        Wife wife = new Wife();
        wife.tellStupidJoke(); // far easier!
        return wife;
    }

Summary

The Stepdown Rule tells us that we should organize our code so that we can read the code top-to-bottom and each function call descends by one level of abstraction. It applies even if a function is used multiple times, there are similar functions in the same class or we’re writing unit tests. Last but not least, whether you choose to use the rule or not, remember to stay consistent! If I understand the key you use to organize functions in classes once, I should be able to use that understanding in any place in the project.

Test data

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

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Create a CLI Chatbot With the ChatGPT API and Node.js
  • Top 5 Data Streaming Trends for 2023
  • Microservices Testing
  • 11 Observability Tools You Should Know

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: