Question

The Single responsibility principle is defined on wikipedia as

The single responsibility principle is a computer programming principle that states that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class

If a class should only have a single responsibility, how can it have more than 1 method? Wouldn't each method have a different responsibility, which would then mean that the class would have more than 1 responsibility.

Every example I've seen demonstrating the single responsibility principle uses an example class that only has one method. It might help to see an example or to have an explanation of a class with multiple methods that can still be considered to have one responsibility.

Was it helpful?

Solution

The single responsibility might not be something that a single function can fulfill.

 class Location { 
     public int getX() { 
         return x;
     } 
     public int getY() { 
         return y; 
     } 
 }

This class may break the single responsibility principle. Not because it has two functions, but if the code for getX() and getY() have to satisfy different stakeholders that may demand change. If Vice President Mr. X sends around a memo that all numbers shall be expressed as floating point numbers and Accounting Director Mrs. Y insists that all numbers her department reviews shall remain integers regardless of what Mr. X thinks well then this class had better have a single idea of who it's responsible to because things are about to get confusing.

If SRP had been followed it would be clear if the Location class contributes to things Mr X and his group are exposed to. Make clear what the class is responsible to and you know which directive impacts this class. If they both impact this class then it was poorly designed to minimize the impact of change. "A class should only have one reason to change" doesn't mean the entire class can only ever do one little thing. It means I shouldn't be able to look at the class and say that both Mr X and Mrs Y have an interest in this class.

Other than things like that. No, multiple methods are fine. Just give it a name that makes clear what methods belong in the class and what ones don't.

Uncle Bob's SRP is more about Conway's Law than Curly's Law. Uncle Bob advocates applying Curly's Law (do one thing) to functions not classes. SRP cautions against mixing reasons to change together. Conway's Law says the system will follow how an organization's information flows. That leads to following SRP because you don't care about what you never hear about.

"A module should be responsible to one, and only one, actor"

Robert C Martin - Clean Architecture

People keep wanting SRP to be about every reason to limit scope. There are more reasons to limit scope than SRP. I further limit scope by insisting the class be an abstraction that can take a name that ensures looking inside won't surprise you.

You can apply Curly's Law to classes. You're outside what Uncle Bob talks about but you can do it. Where you go wrong is when you start to think that means one function. That's like thinking a family should only have one child. Having more than one child doesn't stop it from being a family.

If you apply Curly's law to a class, everything in the class should be about a single unifying idea. That idea can be broad. The idea might be persistence. If some logging utility functions are in there, then they are clearly out of place. Doesn't matter if Mr X is the only one who cares about this code.

The classic principle to apply here is called Separation of Concerns. If you separate all your concerns it could be argued that what's left in any one place is one concern. That's what we called this idea before the 1991 movie City Slickers introduced us to the character Curly.

This is fine. It's just that what Uncle Bob calls a responsibility isn't a concern. A responsibility to him isn't something you focus on. It's something that can force you to change. You can focus on one concern and still create code that is responsible to different groups of people with different agendas.

Maybe you don't care about that. Fine. Thinking that holding to "do one thing" will solve all of your design woes shows a lack of imagination of what "one thing" can end up being. Another reason to limit scope is organization. You can nest many "one thing"s inside other "one thing"s until you have a junk drawer full of everything. I've talked about that before

Of course the classic OOP reason to limit scope is that the class has private fields in it and rather then use getters to share that data around, we put every method that needs that data in the class where they can use the data in private. Many find this too restrictive to use as a scope limiter because not every method that belongs together uses exactly the same fields. I like to ensure that whatever idea that brought the data together be the same idea that brought the methods together.

The functional way to look at this is that a.f(x) and a.g(x) are simply fa(x) and ga(x). Not two functions but a continuum of pairs of functions that vary together. The a doesn't even have to have data in it. It could simply be how you know which f and g implementation you're going to use. Functions that change together belong together. That's good old polymorphism.

SRP is just one of many reasons to limit scope. It's a good one. But not the only one.

OTHER TIPS

The key here is scope, or, if you prefer, granularity. A part of functionality represented by a class can be further separated into parts of functionality, each part being a method.

Here's an example. Imagine you need to create a CSV from a sequence. If you want to be compliant with RFC 4180, it would take quite some time to implement the algorithm and handle all the edge cases.

Doing it in a single method would result in a code which won't be particularly readable, and especially, the method would do several things at once. Therefore, you will split it into several methods; for instance, one of them may be in charge of generating the header, i.e. the very first line of the CSV, while another method would convert a value of any type to its string representation suited for CSV format, while another one would determine if a value needs to be enclosed into double quotes.

Those methods have their own responsibility. The method which checks whether there is a need to add double quotes or not has its own, and the method which generates the header has one. This is SRP applied to methods.

Now, all those methods have one goal in common, that is, take a sequence, and generate the CSV. This is the single responsibility of the class.


Pablo H commented:

Nice example, but I feel it still doesn't answer why SRP allows a class to have more than one public method.

Indeed. The CSV example I gave has ideally one public method and all other methods are private. A better example would be of a queue, implemented by a Queue class. This class would contain, basically, two methods: push (also called enqueue), and pop (also called dequeue).

  • The responsibility of Queue.push is to add an object to the queue's tail.

  • The responsibility of Queue.pop is to remove an object from the queue's head, and handle the case where the queue is empty.

  • The responsibility of Queue class is to provide a queue logic.

A function is a function.

A responsibility is a responsibility.

A mechanic has the responsibility to fix cars, which will involve diagnostics, some simple maintenance tasks, some actual repair work, some delegation of tasks to others, etc.

A container class (list, array, dictionary, map, etc) has the responsibility to store objects, which involves storing them, allowing insertion, providing access, some kind of ordering, etc.

A single responsibility doesn't mean there is very little code/functionality, it means whatever functionality there is "belongs together" under the same responsibility.

Single responsibility does not necessarily mean it only does one thing.

Take for example a User service class:

class UserService {
    public User Get(int id) { /* ... */ }
    public User[] List() { /* ... */ }

    public bool Create(User u) { /* ... */ }
    public bool Exists(int id) { /* ... */ }
    public bool Update(User u) { /* ... */ }
}

This class has multiple methods but it's responsibility is clear. It provides access to the user records in the data store. Its only dependencies are the User model and the data store. It's loosely coupled and highly cohesive, which really is what SRP is trying to get you to think about.

SRP should not be confused with the "Interface segregation principle" (see SOLID). The Interface segregation principle (ISP) says that smaller, lightweight interfaces are preferable to larger more generalized interfaces. Go makes heavy use of ISP throughout its standard library:

// Interface to read bytes from a stream
type Reader interface {
    Read(p []byte) (n int, err error)
}

// Interface to write bytes to a stream
type Writer interface {
    Write(p []byte) (n int, err error)
}

// Interface to convert an object into JSON
type Marshaler interface {
    MarshalJSON() ([]byte, error)
}

SRP and ISP are certainly related, but one does not imply the other. ISP is at the interface level and SRP is at the class level. If a class implements several simple interfaces, it may no longer have just one responsibility.

Thanks to Luaan for pointing out the difference between ISP and SRP.

There is a chef in a restaurant. His only responsibility is to cook. Yet he can cook steaks, potatoes, broccoli, and hundred other things. Would you hire one chef per dish on your menu? Or one chef for each component of each dish? Or one chef who can meet his single responsibility: To cook?

If you ask that chef to do the payroll as well, that’s when you violate SRP.

You're misinterpreting the single responsibility principle.

Single responsibility doesn't equal a single method. They mean different things. In software development we talk about cohesion. Functions (methods) that have high cohesion "belong" together and can be counted as performing a single responsibility.

It's up to the developer to design the system so that the single responsibility principle is fulfilled. One can see this as an abstraction technique and is therefore sometimes a matter of opinion. Implementing the single responsibility principle makes the code mainly easier to test and easier to understand its architecture and design.

Counter-example: storing mutable state.

Suppose you had the simplest class ever, whose only job is to store an int.

public class State {
    private int i;


    public State(int i) { this.i = i; }
}

If you were limited to only 1 method, you could either have a setState(), or a getState(), unless you break encapsulation and make i public.

  • A setter is useless without a getter (you could never read the information)
  • A getter is useless without a setter (you can never mutate the information).

So clearly, this single responsibility necessitates having at least 2 methods on this class. QED.

It's often helpful (in any language, but especially in OO languages) to look at things and organize them from the viewpoint of the data rather than the functions.

Thus, consider the responsibility of a class to be to maintain the integrity of and provide help to correctly use the data it owns. Clearly this is easier to do if all the code is in one class, rather than spread out over several classes. Adding two points is more reliably done, and the code more easily maintained, with a Point add(Point p) method in the Point class than having that elsewhere.

And in particular, the class should expose nothing that could result in inconsistent or incorrect data. For example, if a Point must lie within a (0,0) through (127,127) plane, the constructor and any methods that modify or produce a new Point have the responsibility of checking the values they're given and rejecting any changes that would violate this requirement. (Often something like a Point would be immutable, and ensuring that there are no ways of modifying a Point after it's constructed would then also be a responsbility of the class)

Note that layering here is perfectly acceptable. You might have a Point class for dealing with individual points and a Polygon class for dealing with a set of Points; these still have separate responsibilities because Polygon delegates all responsibility for dealing with anything solely to do with a Point (such as ensuring a point has both an x and a y value) to the Point class.

Licensed under: CC-BY-SA with attribution
scroll top