Open/Closed Principle (O)

The original text of the principle is this:

"You should be able to extend a class's behavior without modifying it."

This essentially means that classes should be open for extension but closed for modification, so it should be possible to extend or override class behavior without having to modify code. Behavior change should be pluggable into the class, either through overriding some methods or injecting some configuration. One excellent example of a framework exhibiting this principle is the Spring Framework.

One common place to use this principle is for algorithms or business logic. In our travel website, let's say we have two requirements:

  • We should be able to bundle airline and hotel reservations into a Trip object.
  • We should be able to calculate the cancellation fee for a trip.

Thus, we can model Trips as a struct with a collection (repository) of reservations, and for the cancellation, have each derived type of reservation compute the cancellation fee, as shown here:

type Trip struct {
reservations []Reservation
}

func (t *Trip) CalculateCancellationFee() float64 {
total:= 0.0

for _, r:= range(t.reservations) {
total += r.CalculateCancellationFee()
}

return total
}

func (t *Trip) AddReservation (r Reservation) {
t.reservations = append(t.reservations, r)
}

In the future, if we have a new type of reservation, as long as it implements the CalculateCancellationFee() method of the reservation interface, the CalculateCancellationFee() method should be calculating the cancellation fee.

..................Content has been hidden....................

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