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 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

  • Solid Testing Strategies for Salesforce Releases
  • Apex Testing: Tips for Writing Robust Salesforce Test Methods
  • A General Overview of TCPCopy Architecture
  • Modes and Modality in Performance Testing

Trending

  • How to Convert XLS to XLSX in Java
  • Beyond ChatGPT, AI Reasoning 2.0: Engineering AI Models With Human-Like Reasoning
  • Mastering Advanced Traffic Management in Multi-Cloud Kubernetes: Scaling With Multiple Istio Ingress Gateways
  • Comprehensive Guide to Property-Based Testing in Go: Principles and Implementation
  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 user avatar
Grzegorz Ziemoński
·
Mar. 28, 17 · Tutorial
Likes (19)
Comment
Save
Tweet
Share
61.4K 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.

Related

  • Solid Testing Strategies for Salesforce Releases
  • Apex Testing: Tips for Writing Robust Salesforce Test Methods
  • A General Overview of TCPCopy Architecture
  • Modes and Modality in Performance Testing

Partner Resources

×

Comments

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: