views:

770

answers:

12

I know about "class having a single reason to change". Now, what is that exactly? Are there some smells/signs that could tell that class does not have a single responsibility? Or could the real answer hide in YAGNI and only refactor to a single responsibility the first time your class changes?

+5  A: 

the methods in your class should be cohesive....they should work together and make use of the same data structures internally. If you find you have too many methods that don't seem entirely well related, or seem to operate on different things, then quite likely you dont have a good single responsibility. Often its hard to initially find responsibilities, sometimes you need to use the class in several different contexts and then refactor the class into two classes as you start to see the distinctions. Sometimes you find that its because you are mixing an abstract and concrete concept together, they tend to be harder to see, again, use in different contexts will help clarify.

Keith Nicholas
+5  A: 

The obvious sign is when your class ends up looking like a Big Ball of Mud, which is really the opposite of SRP (Single responsability principle),

Basically, all the object's services should be focused on carry in out a single responsibility, meaning every time your class change and add a service which does not respect that, you know you "deviating" from the "right" path ;)

The cause is usually due to some quick fixes hastily added to the class to repair some defects. So the reason why you are changing the class is usually the best criteria to detect if you are about to break the SRP.

VonC
+15  A: 

The Single Responsibility Principle

There are many obvious cases, e.g. CoffeeAndSoupFactory. Coffee and soup in the same appliance can lead to quite distasteful results. In this example, the appliance might be broken into a HotWaterGenerator and some kind of Stirrer. Then a new CoffeeFactory and SoupFactory can be built from those components and any accidental mixing can be avoided.

Among the more subtle cases, the tension between data access objects (DAOs) and data transfer objects (DTOs) is very common. DAOs talk to the database, DTOs are serializable for transfer between processes and machines. Usually DAOs need a reference to your database framework, therefore they are unusable on your rich clients which neither have the database drivers installed nor have the necessary privileges to access the DB.

Code Smells

  • The methods in a class start to be grouped by areas of functionality ("these are the Coffee methods and these are the Soup methods").

  • Implementing many interfaces.

David Schmitt
+7  A: 

Well this principle is to be used with some salt.. to avoid class explosion.

A single responsibility does not translate to single method classes. It means a single reason for existence... a service that the object provides for its clients.
A nice way to stay on the road.. Use the object as person metaphor.. If the object were a person, who would I ask to do this? Assign that responsibility to the corresponding class. However you wouldn't ask the same person to do your manage files, compute salaries, issue paychecks, verify financial records.. why would you want a single object to do all these. (its okay if a class takes on multiple responsibilities as long as they are all related and coherent.)

  • If you employ a CRC Card, its a nice subtle guideline, if you're having trouble getting all the responsibilities of that object on a CRC Card, its probably doing too much... a max of 7 would do as a good marker.
  • Another code smell from the refactoring book would be HUGE Classes. Shotgun surgery would be another... making a change to one area in a class causes bugs in unrelated areas of the same class...
  • Finding that you are making changes to the same class for unrelated bug-fixes again and again is another indication that the class is doing too much.
Gishu
You say 'It means a single reason for existence" - I'd nuance that, and say "a single reason to change".
MadKeithV
+5  A: 

A simple and practical method to check single responsibility (not only classes but also method of classes) is the name choice. When you design a class, if you easily find a name for the class that specify exactly what it defines, you're in the right way. A difficulty to choose a name is near always a symptom of bad design.

Pier Luigi
+2  A: 

Perhaps a little more technical than other smells:

  • If you find you need several "friend" classes or functions, that's usually a good smell of bad SRP - because the required functionality is not actually exposed publically by your class.
  • If you end up with an excessively "deep" hierarchy (a long list of derived classes until you get to leaf classes) or "broad" hierarchy (many, many classes derived shallowly from a single parent class). It's usually a sign that the parent class does either too much or too little. Doing nothing is the limit of that, and yes, I have seen that in practice, with an "empty" parent class definition just to group together a bunch of unrelated classes in a single hierarchy.

I also find that refactoring to single responsibility is hard. By the time you finally get around to it, the different responsibilities of the class will have become entwined in the client code making it hard to factor one thing out without breaking the other thing. I'd rather err on the side of "too little" than "too much" myself.

MadKeithV
+11  A: 

write a brief but accurate description of what the class does

if the description contains the word "and" then it needs to be split

Steven A. Lowe
A: 

If you're finding troubles extending the functionality of the class without being afraid that you might end up breaking something else, or you cannot use class without modifying tons of its options which modify its behavior smells like your class doing too much.

Once I was working with the legacy class which had method "ZipAndClean", which was obviously zipping and cleaning specified folder...

+2  A: 

If you end up with MethodA that uses MemberA and MethodB that uses MemberB and it is not part of some concurrency or versioning scheme, you might be violating SRP.

If you notice that you have a class that just delegates calls to a lot of other classes, you might be stuck in proxy class hell. This is especially true if you end up instantiating the proxy class everywhere when you could just use the specific classes directly. I have seen a lot of this. Think ProgramNameBL and ProgramNameDAL classes as a substitute for using a Repository pattern.

Lars Mæhlum
+1  A: 

Here are some things that help me figure out if my class is violating SRP:

  • Fill out the XML doc comments on a class. If you use words like if, and, but, except, when, etc., your classes probably is doing too much.
  • If your class is a domain service, it should have a verb in the name. Many times you have classes like "OrderService", which should probably be broken up into "GetOrderService", "SaveOrderService", "SubmitOrderService", etc.
Jon Kruger
A: 

Martin's Agile Principles, Patterns, and Practices in C# helped me a lot to grasp SRP. He defines SRP as:

A class should have only one reason to change.

So what is driving change?

Martin's answer is:

[...] each responsibility is an axis of change. (p. 116)

and further:

In the context of the SRP, we define a responsibility to be a reason for change. If you can think of more than one motive for changing a class, that class has more than one responsibility (p. 117)

In fact SRP is encapsulating change. If change happens, it should just have a local impact.

Where is YAGNI?

YAGNI can be nicely combined with SRP: When you apply YAGNI, you wait until some change is actually happening. If this happens you should be able to clearly see the responsibilities which are inferred from the reason(s) for change.

This also means that responsibilities can evolve with each new requirement and change. Thinking further SRP and YAGNI will provide you the means to think in flexible designs and architectures.

Theo Lenndorff
A: 

Another rule of thumb I'd like to throw in is the following:

If you feel the need to either write some sort of cartesian product of cases in your test cases, or if you want to mock certain private methods of the class, Single Responsibility is violated.

I recently had this in the following way: I had a cetain abstract syntax tree of a coroutine which will be generated into C later. For now, think of the nodes as Sequence, Iteration and Action. Sequence chains two coroutines, Iteration repeats a coroutine until a userdefined condition is true and Action performs a certain userdefined action. Furthermore, it is possible to annotate Actions and Iterations with codeblocks, which define the actions and conditions to evaluate as the coroutine walks ahead.

It was necessary to apply a certain transformation to all of these code blocks (for those interested: I needed to replace the conceptual user variables with actual implementation variables in order to prevent variable clashes. Those who know lisp macros can think of gensym in action :) ). Thus, the simplest thing that would work was a visitor which knows the operation internally and just calls them on the annotated code block of the Action and Iteration on visit and traverses all the syntax tree nodes. However, in this case, I'd have had to duplicate the assertion "transformation is applied" in my testcode for the visitAction-Method and the visitIteration-Method. In other words, I had to check the product test cases of the responsibilities Traversion (== {traverse iteration, traverse action, traverse sequence}) x Transformation (well, codeblock transformed, which blew up into iteration transformed and action transformed). Thus, I was tempted to use powermock to remove the transformation-Method and replace it with some 'return "I was transformed!";'-Stub.

However, according to the rule of thumb, I split the class into a class TreeModifier which contains a NodeModifier-instance, which provides methods modifyIteration, modifySequence, modifyCodeblock and so on. Thus, I could easily test the responsibility of traversing, calling the NodeModifier and reconstructing the tree and test the actual modification of the code blocks separately, thus removing the need for the product tests, because the responsibilities were separated now (into traversing and reconstructing and the concrete modification).

It also is interesting to notice that later on, I could heavily reuse the TreeModifier in various other transformations. :)

Tetha