Issues with inheritance to make your code reusable

When it comes to reusing certain classes for the behavior, we may be tempted to take a base class for a ‘default’ behavior, extend it through a child class and override its methods with additional functionality; something we call inheritance. There are some cases when this is perfectly fine. However, when it comes to code that is on continuous maintenance, issues with this will arrive sooner or later. Let’s have a look at them.

Tight coupling. The first one is quite obvious: it creates tight coupling between your class and its parent. Let’s look at an example adapted to Kotlin, based from Java Design:

In this example, you create an AccountType class from which you inherit a method for calculating interest. And, if you want to calculate interest in a different way or put some process in between, then you can simply override the method.

The problem is that, should you want to create more account types, and decide that some of them should have the same interest calculation from stocks instead of the default one, then you’re going to have to duplicate the overridden method from the Stocks class, leaving you with duplicated code, somewhat defeating the purpose of what you’ve made through inheritance. And say that, with time, the account types that use the Stocks class’s method become more numerous, so that it makes more sense to implement it as default. Then you would have to modify the base calculateInterest() method from AccountType, which is a big no-no from the Open-Closed Principle:

Open-Closed Principle: “Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification.”

#kotlin #android #delegation #design-patterns #development

Delegation Pattern in Kotlin
1.10 GEEK