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
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • When Your Benchmark Leaks the Answer
  • A Practical Pipeline for Identifying Sensitive Columns Before Test Data Masking
  • Generate Random Test Data in PostgreSQL

Trending

  • Fix the Target, Precompute Once: A Backend-Free Word-Ladder Solver With a BFS Distance Field
  • Guess the Speed: Building a Family Internet Speed Guessing Game
  • How to Build Your Own AI SRE From Scratch
  • AI Agents Need an Identity Plane: Rethinking Enterprise Authorization for Autonomous Software

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  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!

By 
Grzegorz Ziemoński
·
Mar. 28, 17 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
65.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Testing Java and Spring Applications With Kotlin: Low-Risk to Adoption
  • When Your Benchmark Leaks the Answer
  • A Practical Pipeline for Identifying Sensitive Columns Before Test Data Masking
  • Generate Random Test Data in PostgreSQL

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook