Search code examples
javadesign-patternssolid-principlesinterface-segregation-principle

Opposite of Interface Segregation Principle


I was asked today in a interview what is the Interface Segregation Principle and what is the opposite case or principle to this one.

The ISP is clear for me but I don't know the second part of the question, what is the opposite principle to the ISP?


Solution

  • From Wikipedia:

    The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use.

    The opposite of that would be a client that is forced to depend on methods that it doesn't use. This might manifest itself in either implementing an interface that it doesn't require, the interface having methods at too broad of a layer, or a class that has several abstract methods defined that are not necessary to the client.

    An example (first with interfaces):

    public interface Book {
    
        String getAuthor();
        String getGenre();
        String getPageCount();
        String getWeight();
    }
    
    public interface EBook extends Book {
        // Oh no - ebooks don't have weight, so that should always return zero!
        // But it makes no sense to include it as an attribute of the interface.
    }
    

    An example with abstract methods:

    public abstract class Shape {
    
        public abstract double getVolume();
        public abstract double getHeight();
        public abstract double getLength();
        public abstract double getWidth();
        public abstract Color getColor();
    }
    
    public class Line extends Shape {
    
        public double length;
        public Color color;
    
        // Kind of forced to have a volume...
        public double getVolume() {
            return 0;
        }
    
        /// ...and a height...
        public double getHeight() {
            return 0;
        }
    
        // ...and a width...
        public double getWidth() {
            return 0;
        }
    
        public double getLength() {
            return length;
        }
    
        public Color getColor() {
            return color;
        }
    }