I have some troubles with understanding these two principles. This is a bit long-read-question, so be patient.
Lets assume that we have a class
abstract class Shape {
abstract void onDraw();
}
and interface
interface SideCountable {
int getSidesCount();
}
And then we create two children classes
class Quad extends Shape {
@Override
public void onDraw() {
//some draw logic here
}
}
class Triangle extends Shape {
@Override
public void onDraw() {
//some draw logic here
}
}
And now we will make Shape
implements SideCountable
abstract class Shape implements SideCountable{
abstract void onDraw();
}
and make changes in children classes
class Quad extends Shape {
@Override
public int getSidesCount() {
return 4;
}
@Override
public void onDraw() {
//some draw logic here
}
}
class Triangle extends Shape {
public int getSidesCount() {
return 3;
}
public void onDraw() {
//some draw logic here
}
}
And create test function for this structure (following LSP) :
public void printSidesCount(List<Shape> shapes) {
for(int i=0; i < shapes.size(); i++) {
System.out.println(shapes.get(i).getSidesCount());
}
}
And here I want to stop because actually in the next step I was stucked.
What if we'll create a third class Circle
?
class Circle extends Shape {
public int getSidesCount() {
return ???;
}
@Override
public void onDraw() {
//some draw logic here
}
}
Circle has no sides, so implementation of SideCountable
for this children sounds ridiculous. Ok, we can move implementation to Quad and Triangle only, but in this case LSP will not working anymore. Can someone describe what the best way I should to do?
- Leave
SideCountable
inShape
class and return 0 forCircle
and break interface segregation principle? - Move
SideCountable
toQuad
andTriangle
and break LSP principle?