educative.io

OOD SOLID ISP example solution is confusing

Hello,
Isn’t Shape3D interface is forced to implement methods like area() which doesn’t apply to it?


Course: https://www.educative.io/collection/10370001/5583710957338624
Lesson: https://www.educative.io/collection/page/10370001/5583710957338624/6500211344277504

Yes, you are correct. The Shape3D interface is forced to inherit the area() method from the Shape interface, which might not be applicable to 3D shapes. This is indeed a violation of the Interface Segregation Principle (ISP).

The Interface Segregation Principle suggests that a class should not be forced to implement methods it does not use. In this case, the Shape3D interface should only contain methods relevant to 3D shapes, and the area() method, which is specific to 2D shapes, should not be part of it.

To adhere to the ISP, the design should be revised by separating the interfaces for 2D and 3D shapes. Each interface should contain only the methods relevant to its specific set of classes. Here’s a corrected version of the solution:

// Interface for 2D shapes
interface Shape {
    double calculateArea();
}

// Interface for 3D shapes
interface Shape3D {
    double calculateVolume();
}

// Square class implementing Shape
class Square implements Shape {
    // Implement calculateArea() here
}

// Rectangle class implementing Shape
class Rectangle implements Shape {
    // Implement calculateArea() here
}

// Cube class implementing Shape3D
class Cube implements Shape3D {
    // Implement calculateVolume() here
}

Now, the Shape3D interface only contains the relevant method calculateVolume(), which is suitable for 3D shapes, and there is no violation of the Interface Segregation Principle. The Shape interface contains the method calculateArea(), which is appropriate for 2D shapes. This separation ensures that classes implementing these interfaces only need to implement the methods that are relevant to them.

1 Like

Hey There,

I agree to the part where you say 3d shapes are forced to implement area method.
But IMO you are not 100% correct here.
Every 3D shape also has an area called Surface Area.
My suggestion it to specify that the area method in 3d objects means Surface Area rather than just Area.