search
Get Started
search
Replace Inheritance with Delegation - Jetbrains Native Refactoring
zoom_in Click to enlarge

Replace Inheritance with Delegation

language

description Replace Inheritance with Delegation Overview

Replace Inheritance with Delegation is a software refactoring technique available in JetBrains IDEs that transforms a subclass relationship into a delegation relationship. When applied, the tool creates a separate instance of the parent class within the former subclass, which then delegates work to this instance rather than inheriting behavior directly. This refactoring is particularly useful when inheritance creates tight coupling between classes or when the relationship doesn't represent a true 'is-a' relationship in object-oriented design.

help Replace Inheritance with Delegation FAQ

How do I use 'Replace Inheritance with Delegation' in IntelliJ IDEA?

In IntelliJ IDEA, you can access this refactoring by placing your cursor on the extends declaration or the class name, then navigating to Refactor > Replace Inheritance with Delegation (or using the keyboard shortcut). The IDE will create a field holding an instance of the former superclass and rewrite method calls to delegate to that instance.

Why would I use Replace Inheritance with Delegation instead of keeping inheritance?

This refactoring is useful when a subclass only uses a small portion of its parent class's behavior, or when the inheritance hierarchy is creating tight coupling that makes testing and maintenance difficult. By switching to delegation, you gain flexibility to swap implementations at runtime and reduce the fragile base class problem.

Does 'Replace Inheritance with Delegation' work in WebStorm and other JetBrains IDEs?

Yes, this refactoring is available across JetBrains IDEs that support object-oriented languages, including IntelliJ IDEA, WebStorm for TypeScript/JavaScript, and PyCharm for Python. The availability and exact menu location may vary depending on the language and context of your code.

Will Replace Inheritance with Delegation break my existing unit tests?

It can break tests if they rely on polymorphic behavior where the subclass is passed as an instance of the superclass type. After the refactoring, the former subclass is no longer a subtype, so any code expecting the parent type will need to be updated to accept the new delegated interface.

Reviews & Comments

Write a Review

rate_review

Be the first to review

Share your thoughts with the community and help others make better decisions.

Save to your list

Save your favorites and follow how their scores change over time.

Save favorites
Track changes
Compare scores

Already have an account? Sign in

Compare Items

See how they stack up against each other

Comparing
VS
Select 1 more item to compare