Last Revision — April 19, 2022
1 Min Read
Duplicate Abstraction
Object Oriented Abusers
Duplication
Between Classes
- Oddball Solution (family)
- Duplicated Code (co-exist)
Martin Fowler in book (1999): "Refactoring: Improving the Design of Existing Code"
If two classes have the same functionality but different implementations, developers should merge them, or developers should extract a superclass to limit Code Duplication. This smell occurs whenever a class can operate on two alternative classes (for example, take Zombie
and Snowman
). However, the interface to these alternative classes is different - when it operates with Zombie
, it calls hug_zombie()
, and with Snowman
, it has to call hug_snowman()
.
This may happen due to the oversight that a functionally equivalent class already exists or when two or more developers are working on code to handle a similar situation. However, they did not know about the other's work — lack of abstract methods that enforce the common implementation method names.
DRY Principle - as the name suggests - is aimed to reduce repetition of the same code implementations.
Each individual of Humanoid have similar but personalised logic but under different method names
class Snowman(Humanoid):
def hug_snowman():
...
class Zombie(Humanoid):
def hug_zombie():
...
Use common method.
class Snowman(Humanoid):
def hug():
...
class Zombie(Humanoid):
def hug():
...