Single Responsibility Principle (S)

The principle states the following:

"One class should have one, and only one, responsibility."

While this seems obvious, it is important to have discipline to maintain this principle in the face of the ever-increasing complexity of product requirements. For example, on our travel website, let's say we model a ticket using an entity struct (entity classes are a representation of persistent objects in memory; they present the data). Initially, the company did only airline reservations and the ticket was modeled as such. However, after some time, the product had requirements for hotel reservations or bus tickets. With the knowledge of the new requirements, our previous design might not be the best one possible. When such new requirements arise, it is important to refactor code to stay true to the guidelines mentioned here.

So, in this specific example, instead of clubbing the ticket semantics of all business verticals, it is important to build a hierarchy with say reservation as the base class and AirlineTicket, BusTicket, and HotelReservations as all the derived classes. Patterns to build such a hierarchy are described later in the chapter. An example of the reservation interface is shown here:

type Reservation interface {
GetReservationDate() string
CalculateCancellationFee() float64
Cancel()
GetCustomerDetails() []Customer
GetSellerDetails() Seller
}

Of course, this is a very minimal set of methods for illustrative purposes only. When the client code does not care about the type of the reservation, extraneous coupling is not introduced.

Besides classes, this principle is more important in package design. For example, packages named utils become a dumping ground of miscellaneous functions. Such a name and collection should be avoided. On the other hand, some examples of good package names from the Go standard library, which clearly indicate the purpose, are as follows:

  • net/http: this provides http clients and servers.
  • encoding/json: this implements JSON serialization/deserialization.
..................Content has been hidden....................

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