INTRODUCTION
I work on my master thesis about inheritance problems and work out some indicators which show that an inheritance problem exist.
Like the following example:
EXAMPLE
public static String getAnimalNoise(Animal animal) {
if (animal instanceof Dog)
return "Woof";
if (animal instanceof Cat)
return "Miau";
return "";
}
The method returns the String "Woof"
if the given Animal instance is a Dog
and "Miau"
if it is a Cat
. The empty string because some animals make no noises at all.
So the correct solution for that should be use polymorphism with a getNoise
Method in the Animal class.
I have analysed different indicators of inheritance problems and want to say if some of them violates a SOLID Principle.
I thought the example above violates the:
- Single responsibility principle (SRP)
- Open/closed principle (OCP)
- Liskov substitution principle (LSP)
- Dependency inversion principle (DIP)
But i'm not really sure whether it is true for all.
I thought:
PRINCIPLE VIOLATIONS
SRP Violation
Because conditional statements at all violates the SRP, because like the switch case statement or more than one if-else statement are consider more than one responsibility.
It exists two cases so there are more than one reason to change the method.
OCP Violation
Because if a new animal is added a new case must be added to the method so the Method is not close for modifications.
LSP VIOLATION
Each branch executes different actions dependent of the animal sub type. Which i think violates the LSP ?! I know the example of the rectangle and square and the getArea but these example i thought fits also to the violation.
DIP VIOLATION
The conditional statements take dependency that means the statements are dependent on details and not on abstractions which violates the DIP.
QUESTION:
So the Question is, for the given example, are the given principles really violated and is the reasoning correct?