By using this site, you agree to the Privacy Policy and Terms of Use.
Accept
World of SoftwareWorld of SoftwareWorld of Software
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Search
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
Reading: Here’s Why You Should Replace Inheritance with Delegation | HackerNoon
Share
Sign In
Notification Show More
Font ResizerAa
World of SoftwareWorld of Software
Font ResizerAa
  • Software
  • Mobile
  • Computing
  • Gadget
  • Gaming
  • Videos
Search
  • News
  • Software
  • Mobile
  • Computing
  • Gaming
  • Videos
  • More
    • Gadget
    • Web Stories
    • Trending
    • Press Release
Have an existing account? Sign In
Follow US
  • Privacy
  • Terms
  • Advertise
  • Contact
Copyright © All Rights Reserved. World of Software.
World of Software > Computing > Here’s Why You Should Replace Inheritance with Delegation | HackerNoon
Computing

Here’s Why You Should Replace Inheritance with Delegation | HackerNoon

News Room
Last updated: 2025/02/17 at 4:14 PM
News Room Published 17 February 2025
Share
SHARE

Transform your rigid inheritance into flexible delegations

TL;DR: Replace restrictive inheritance hierarchies with flexible object delegation

Problems Addressed 🤯

  • Liskov substitution violation
  • Rigid class hierarchy
  • Hidden dependencies
  • Tight Coupling
  • Limited Reusability
  • Single Responsibility principle violation

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-iii-t7h3zkv

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xiv

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-vii-8dk31x0

https://hackernoon.com/how-to-find-the-stinky-parts-of-your-code-part-xxv

Steps 🔄

  1. Create a temporary field in the subclass for the superclass.
  2. Update subclass methods to delegate calls.
  3. Add delegation methods for inherited behavior.
  4. Remove inheritance and update object creation.

Sample Code 💻

Before 🚨

class Chatbot {    
    public void respond(String question) {
        // Here is the logic to answer a question
    }
}

class Robot extends Chatbot {
    // The Physical Robot inherits the logic
    // to answer questions
    // and adds physical behavior
    public void move() {
        System.out.println("Moving...");
    }
    
    public void grab() {
        System.out.println("Grabbing object...");
    }
}

After

class Brain {
    public String answer(String question) {
        // The common logic to answer questions
        // is extracted into a different object
        return "Thinking... Answering: " + question;
    }
}

final class Chatbot {    
    private final Brain brain;
    
    Chatbot(Brain brain) {
        this.brain = brain;
    }
    
    public void respond(String question) {
        System.out.println(this.brain.answer(question));
    }
}

final class Robot {
    // 4. Remove inheritance and update object creation.
    private final Brain brain;    
    // 1. Create a temporary field in the subclass for the superclass.
    // private final Chatbot chatbot;  
    
    Robot(Brain brain) {
        this.brain = brain;
        // 2. Update subclass methods to delegate calls.
        // this.chatbot = new Chatbot(brain);
        // This code is removed after step 4
    }
    
    public void move() {
        System.out.println("Moving...");
    }
    
    public void grab() {
        System.out.println("Grabbing object...");
    }
    
    public void respond(String question) {
        // 3. Add delegation methods for inherited behavior.
        // chatbot.respond(question);
        // This code is also removed after step 4 
        System.out.println(this.brain.answer(question));
        // The physical robot can also use it as text-to-speech
    }
}

Type 🛠️

Safety 🛡️

This refactoring is safe when done carefully and with proper testing.

You should ensure all delegated method signatures match exactly and maintain existing behavior.

The main risk comes from missing methods that need delegation or incorrectly implementing the delegation methods.

Why is the Code Better? ✨

You gain the flexibility to change implementations at runtime and avoid the pitfalls of inheritance like tight coupling.

How Does it Improve the Bijection?

This refactoring improves the Bijection between code and reality by better modeling real-world relationships.

A robot doesn’t inherit from a brain in the real world – it has a brain.

By replacing inheritance with delegation, you create a more accurate representation of the actual relationship between objects using the MAPPER.

Limitations ⚠️

The rewriting requires writing additional delegation methods.

If subclass logic relies too much on the superclass, delegation might increase boilerplate.

Refactor with AI

See also 📚

Credits

Image by Gerd Altmann on Pixabay


This article is part of the Refactoring Series.

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Share This Article
Facebook Twitter Email Print
Share
What do you think?
Love0
Sad0
Happy0
Sleepy0
Angry0
Dead0
Wink0
Previous Article macOS Tip: Set Up and Control Hot Corners With Modifier Keys
Next Article https://news.google.com/read/CBMiugFBVV95cUxPbzhyTG9uaWYwWEhhWnpfTTZ5RXNjT0pJb3FsaXR3TThuVjlWRWg3NnZNY3lVaVdseDY2OXEwSHB0bWJZcEIzeDBXcUswWXFWYjBJd1NuZUhEVHkzeUNfbWg1TUtvWVVGTzE1MTVvZ2UwTTZvVlNCRmRObXpFT0NFWDJ4MGtLYUtWQ0VkM0tEMU43RTdfY2NtMTlacmFTUmNydVpZY29Udm1FaGFSbEpER1g2WHpvN1YxcVE?hl=en-GB&gl=GB&ceid=GB%3Aen
Leave a comment

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Stay Connected

248.1k Like
69.1k Follow
134k Pin
54.3k Follow

Latest News

Two facilites to produge 3-nanometer chips unveiled in Noida, Bengaluru
Software
Three worlds in 2035: Imagining scenarios for how the world could be transformed over the next decade
News
EXCLUSIVE: Government calls in tech firms to roll out digital IDs – UKTN
News
I’ve got a soft spot for the electric Renault 4 – here’s why you’ll feel the same | Stuff
Gadget

You Might also Like

Computing

Why I Ditched JavaScript and Built a SaaS Stack With HTMX, Go & Postgres That Just Works | HackerNoon

8 Min Read
Computing

Horabot Malware Targets 6 Latin American Nations Using Invoice-Themed Phishing Emails

4 Min Read
Computing

Oracle Talks Up Its Adaptived Daemon For Linux Systems

1 Min Read
Computing

China’s JD.com locked in heated  battle for food delivery supremacy as regulators urge fair competition · TechNode

4 Min Read
//

World of Software is your one-stop website for the latest tech news and updates, follow us now to get the news that matters to you.

Quick Link

  • Privacy Policy
  • Terms of use
  • Advertise
  • Contact

Topics

  • Computing
  • Software
  • Press Release
  • Trending

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

World of SoftwareWorld of Software
Follow US
Copyright © All Rights Reserved. World of Software.
Welcome Back!

Sign in to your account

Lost your password?