Interface Segregation Principle (I)

This principle states this:

"Many client-specific interfaces are better than one general-purpose interface."

As our code evolves, it is a common symptom for base classes to be a collect-all for behavior. However, this makes the whole code brittle: derived classes have to implement methods that don't make sense to them. Clients also can get confused by this variable nature of derived classes. To avoid this, this principle recommends having an interface for each type of client.

For example, in the preceding reservation example, let's say we have a fat reservation base class for all airline, hotel, bus tickets, and so on. Now suppose airline reservations have a special method; say, AddExtraLuggageAllowance(), which allows the ticket holder to carry extra luggage. With a hotel reservation, we need the ability to change the room type—ChangeType(). With a naive design, all these methods would be stuffed in the base reservation class, with derived classes having to implement unrelated methods. A better design is to have the base reservation class just deal with the common behavior and have specific interfaces for airline, bus, and hotel reservations:

type Reservation interface {
GetReservationDate() string
CalculateCancellationFee() float64
}

type HotelReservation interface {
Reservation
ChangeType()
}

type FlightReservation interface {
Reservation
AddExtraLuggageAllowance(peices int)
}

type HotelReservationImpl struct{
reservationDate string
}

func (r HotelReservationImpl) GetReservationDate() string {
return r.reservationDate
}

func (r HotelReservationImpl) CalculateCancellationFee() float64 {
return 1.0 // flat:P
}

type FlightReservationImpl struct{
reservationDate string
luggageAllowed int
}

func (r FlightReservationImpl) AddExtraLuggageAllowance(peices int) {
r.luggageAllowed = peices
}


func (r FlightReservationImpl) CalculateCancellationFee() float64 {
return 2.0 // flat but slight more than hotels:P
}


func (r FlightReservationImpl) GetReservationDate() string {
// this might look repetitive, but the idea is to provide freedom for the
// derived classes to flux independently of each other
return r.reservationDate
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset