Tuesday, September 17

Interface Segregation Principle(ISP) - Java design principals , OOPS design principals ,Object oriented design principals , How to design interface in java







Interface Segregation Principle stats that, a client should not implement an interface, if it doesn't use that.

What exaclt does that mean ?

Let's understand this

Consider there is one interface Travel

Travel has two methods

travelbyBus()

travelByTrain()


Now there is one class Passenger . Passenger will always travel by bus .
 

if Passenger class implements Travel interface

Passenger implements Passenger {

travelbyBus(){
}

travelByTrain(){
}

}


It is forced to implement both the methods travelByBus() and travelByTrain() , thought Passenger has nothing to do with travelByTrain().


Now lets read the principal again

Interface Segregation Principle stats that, a client should not implement an interface, if it doesn't use that.

Client Passenger should not be forced to implement travelByTrain() method as it never needs it.








Here comes the Interface designing best practice .

An interface design should be very thoughtful. It should always take in consideration all its possible clients and should always make interface design client friendly.


So could that be achieved?

 Instead of creating one interface for both methods , two separate interfaces could be designed

like :

BusTravel{

travelByBus();
}


TrainTravel{

travelByTrain();
}



Passenger class can implement BusTravel interface and will not be forced to implement anymore method.




Thus Interface Segregation Principle(ISP) basically recommend to design the interfaces taking in consideration holistic ststem and all poosible clients.

No comments:

Post a Comment