Logo

dev-resources.site

for different kinds of informations.

Code Smell 286 - Overlapping Methods

Published at
1/16/2025
Categories
webdev
programming
php
inheritance
Author
mcsee
Author
5 person written this
mcsee
open
Code Smell 286 - Overlapping Methods

When parent and child methods collide

TL;DR: Avoid using private methods in parent classes with names that child classes can use.

Problems

  • The least surprise principle violation

  • Unexpected behavior and defects

  • Hidden dependencies

  • Limited extensibility

  • Code ambiguity

  • Open/Closed principle violation

  • Misleading design

Solutions

  1. Avoid hierarchies
  2. Rename private methods
  3. Maintain clear naming
  4. Avoid overlapping names
  5. Avoid protected methods
  6. Subclassify for essential relations, not to reuse code

Context

When you use the same method name in parent and child classes, you create confusion.

A private method in the parent class cannot be overridden even if a public method with the same name exists in the child class.

This is a problem most static languages have in their design

This disconnect leads to bugs and makes your code hard to maintain.

Sample Code

Wrong

<?

class ParentClass {
    private function greet() {
        // This method is private
        return "Hello from ParentClass";
    }

    public function callGreet() {
        return $this->greet();
    }
}

class ChildClass extends ParentClass {
    public function greet() {
        // Overriding a concrete method is a code smell
        // Compilers SHOULD warn you
        return "Hello from ChildClass";
    }
}

$child = new ChildClass();
echo $child->callGreet();

// When callGreet() is invoked on the $child object,
// it executes the following:
// It calls $this->greet(), 
// which refers to the greet() method of ParentClass 
// because the original method is private 
// and cannot be overridden or accessed from ChildClass.

// The unexpected output is 'Hello from ParentClass'
Enter fullscreen mode Exit fullscreen mode

Right

<?

class ParentClass {
    protected function greet() {
        // notice the 'protected qualifier'
        return "Hello from ParentClass";
    }

    public function callGreet() {
        return $this->greet();
    }
}

class ChildClass extends ParentClass {
    public function greet() {
        return "Hello from ChildClass";
    }
}

$child = new ChildClass();
echo $child->callGreet();

// The output is "Hello from ChildClass"
// This is the standard (and wrong) solution
// Also fixed by most AIs
Enter fullscreen mode Exit fullscreen mode
<?

abstract class ParentClass {
    // Declare greet() as an abstract method
    // Following the template-method design pattern
    abstract protected function greet();

    public function callGreet() {
        return $this->greet();
    }
}

class ChildClass extends ParentClass {
    protected function greet() {
        return "Hello from ChildClass";
    }
}

class OtherChild extends ParentClass {
    protected function greet() {
        return "Hello from OtherChild";
    }
}

$child = new ChildClass();
echo $child->callGreet(); // Output: Hello from ChildClass

$otherChild = new OtherChild();
echo $otherChild->callGreet(); // Output: Hello from OtherChild
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Semi-Automatic

You can detect this smell by looking for private methods in parent classes and checking if child classes define methods with the same name.

You must also test parent methods calling private methods.

Tags

  • Hierarchy

Level

[X] Intermediate

Why the Bijection Is Important

Clear and predictable code should reflect the real-world hierarchy it models.

When you use private methods with overlapping names, you create a Bijection gap between the model and the implementation.

This gap confuses developers, increases defects, and violates clean code principles.

AI Generation

AI generators often create this smell when they generate boilerplate parent-child relationships.

They might not check access levels or consider inheritance implications.

AI Detection

AI tools can fix this smell with clear instructions.

You can ask the AI to check for overlapping method names and refactor hierarchies.

Try Them!

Remember: AI Assistants make lots of mistakes

Without Proper Instructions With Specific Instructions
ChatGPT ChatGPT
Claude Claude
Perplexity Perplexity
Copilot Copilot
Gemini Gemini

Conclusion

When designing parent and child classes, you should use methods that clearly define inheritance and accessibility.

Avoid private methods that overlap with child methods.

This keeps your code readable, extensible, and aligned with clean code principles.

Languages like Python allow you to override parent methods regardless of their names, while Java strictly enforces access levels.

C# behaves similarly to Java.

These differences mean you need to understand the specific rules of the language you are working with to avoid unexpected behavior.

Relations

Disclaimer

Code Smells are my opinion.

Credits

Photo by Matt Artz on Unsplash


Inheritance is good, but you should never forget that it introduces tight coupling.

Robert C. Martin


This article is part of the CodeSmell Series.

programming Article's
30 articles in total
Programming is the process of writing, testing, and maintaining code to create software applications for various purposes and platforms.
Favicon
What ((programming) language) should I learn this year, 2025 ?
Favicon
7 Developer Tools That Will Boost Your Workflow in 2025
Favicon
Designing for developers means designing for LLMs too
Favicon
Introduction to TypeScript for JavaScript Developers
Favicon
Filling a 10 Million Image Grid with PHP for Internet History
Favicon
When AI Fails, Good Documentation Saves the Day 🤖📚
Favicon
Is JavaScript Still Relevant?
Favicon
Daily JavaScript Challenge #JS-74: Convert Hexadecimal to Binary
Favicon
Code Smell 286 - Overlapping Methods
Favicon
Searching vs. Sorting in Java: Key Differences and Applications
Favicon
Easy Discount Calculation: Tax, Fees & Discount Percentage Explained
Favicon
Securing Sensitive Data in Java: Best Practices and Coding Guidelines
Favicon
Golang - How a Chef and Waiter Teach the Single Responsibility Principle
Favicon
[Boost]
Favicon
How to Resolve the 'Permission Denied' Error in PHP File Handling
Favicon
7 Mistakes Developers Make When Learning a New Framework (and How to Avoid Them)
Favicon
Python в 2025: стоит ли начинать с нуля? Личный опыт и рекомендации
Favicon
Cómo gestionar tus proyectos de software con Github
Favicon
2429. Minimize XOR
Favicon
Decreasing server load by using debouncing/throttle technique in reactjs
Favicon
➡️💡Guide, Innovate, Succeed: Becoming a Software Development Leader 🚀
Favicon
Debugging Adventure Day 1: What to Do When Your Code Doesn’t Work
Favicon
🚀 New Book Release: "Navigate the Automation Seas" – A Practical Guide to Building Automation Frameworks
Favicon
Build a Secure Password Generator with Javascript
Favicon
join my project semester simulator
Favicon
Как создать свой VPN и получить доступ ко всему?
Favicon
Основы изучения Python: Руководство для начинающих
Favicon
Revolutionary AI Model Self-Adapts Like Human Brain: Transformer Shows 15% Better Performance in Complex Tasks
Favicon
Breakthrough: Privacy-First AI Splits Tasks Across Devices to Match Central Model Performance
Favicon
Flow Networks Breakthrough: New Theory Shows Promise for Machine Learning Structure Discovery

Featured ones: