I have YoutubeVideoService class which does CRUD(Create, Read, Update, and Delete) operations. In my view Create, Read, Update, and Delete are four reasons for a class to change. Does this class violates Single Responsibility Principle?
If it violates, then should we have four classes like CreateYoutubeVideoService, ReadYoutubeVideoService, UpdateYoutubeVideoService and DeleteYoutubeVideoService. Isn't it an overkill to have lots of classes?
I think you're taking the Single Reposibility Principle a bit to the extreme on a class level, without taking into consideration cohesion.
If you follow that route, you could justify having lots of classes with just one or two methods, which in turn would increase the number of dependencies to the sky.
I think the spirit of SRP is Simplify as much as you can, but not more.
How long should a method be? One could say there is no reason to have more than 2 lines. But this is certainly overkill in some situations. Same with SRP - you have to decide when enough is enough. CRUD looks like a cohesive set of operations which are perfectly fit for single class, because they operate on same type of data.
A good way of measuring coherence to the Single Responsibility Principle is to think about how many reason to change this class has. If you can think more than one reason to change, probably it's violating the SRP.
The only reason to change a CRUD class like this, is a change in the underlaying data structure. So this respects the SRP.
On the other hand, if you had in that class any other operation (es. checking the video length or type before inserting it), that would violate SRP, since it could change independently from the persistency layer.
SRP is not a dogma, when following SOLID principles, we always have to be careful to not introduce needles complexity. As per Bob Martin's masterpiece, speaking about when two responsibility should be separated:
If, on the other hand, the application is not changing in ways that cause the two responsibilities to change at different times, there is no need to separate them. Indeed, separating them would smell of needless complexity.
(…) is not wise to apply SRP (or any other principle, for that matter) if there is no symptom.
Service classes are SRP killers. By definition they are an aggregation of operations - which is contrary to SRP. Often single method of the service would require some dependency, that all other methods might not care at all, then with each such method dependencies multiply, it leads to mess. Manager, Service, sometime Repository - these patterns are plain bad from dependencies point of view. In Commands/Queries/Requests world you would have these 3 commands and a query just grouped into a domain/directory. That leads to cleaner, smaller, easier to read and extendable code. Also to cleaner processes.
Related
According to Vaughn Vernon's IDDD_Samples, a repository interface has some methods: issuing an identity(nextIdentity), saving an entity(save), getting an entity(productOfId), removing an entity(remove) and so on.
However, it is rare to use all the methods in a single use-case. For example, in the case of creating a new entity, two methods nextIdentity and save is used, but the others are not used.
From the point of view of Interface Segregation Principle, I thought that the methods of the repository should be separated into some interfaces. How does this help?
My long-winded answer to another question boiled down to minimizing the ability of a client from doing the "wrong" thing.
Smaller interfaces introduced and used at the "right" times can prevent a number of bugs and accidental issues developers may incur.
This means your instincts are leading you to the right direction. You can pass these "smaller" interfaces via dependency injection or other means to components that have a more narrow scheme of what they need to do (i.e. components designed for each use case). This prevents you or others from doing something you "shouldn't" automatically.
From the point of view of Interface Segregation Principle, I thought that the methods of the repository should be separated into some interfaces. How does this help?
I would describe it this way: Interface Segregation comes at a cost.
In this case, segregating this interface introduces eight? new role interfaces that each need to be managed. Possibly more, possibly fewer, depending on how many distinct use cases we are trying to manage, and how much fine grained control we want to support.
My suspicion is that, for Vernon's purposes, what he wants is the banana -- a clear demonstration of the responsibilities of repositories without dragging in the gorilla and the rest of the jungle.
Another way of expressing the same idea: the responsibilities here have a lot of cohesion -- when you replace your persistence solution, it is likely that the implementation of all of these responsibilities will need to change, and it is natural that they change together.
The best fit solution for a tutorial, where you are trying to present to a student a single idea, and the best fit solution for a living system, where you frequently need to make fine grained changes to the implementation of responsibilities, are not necessarily the same.
Horses for courses.
I have problem in understanding Single Responsibility Principle . Should SRP be applied at class level or at method level.
Lets say i have Student Class ,i need to create student , update student and delete student.
If I create a service class that has methods for these three actions does this break SRP principle.
SRP is at both at class and method level.So if you ar talking about student class then only responsibility it has in this case to do CRUD on student entity.At the same time when you talk about methods the you should not have an InsertStudent method and do both Update and Insert in it based on ID .That breaks SRP.But if you have InsertStudent which inserts and UpdateStudent which updates it follows SRP
I'd say you have a service class which is responsible for CRUD operations on objects of type Student. I don't see this design to violate SRP at all.
Quoting from http://www.developerfusion.com/article/137636/taking-the-single-responsibility-principle-seriously/
Two methods of the same class (or even different classes) should focus on different aspects. However, two methods in the same class, e.g. a repository, likely will both have to be concerned with the same higher level responsibility, e.g. persistence.
I see CRUD as well-known operations within a single context unless you have some business associated with it. For example you might want to allow some classes to only be able to read data and deny them from making any changes to it. That's when you can make use of another SOLID principle Interface segregation.
You can define an interface with only read method defined to be used in those classes. Or if it makes sense (performance-wise for example), create a separate concrete class that just implements read operation.
Not to criticize because I believe in the principal, but don't follow the advice that says it fits if you can summarize the functionality without using "and". With this kind of logic you could still have an enormous one file application and say its responsibility without using "and". A web browser is a complicated piece of software but you can still describe it in one short statement. And it makes total sense because the thing is like a pyramid and you should always be able to describe the top level regardless of the parts being split or not.
That is precisely what we do everyday with functions. You pick a very simple function name which hides the complexity like "connect" for a socket. You actually don't know from this point of view if it is split afterwards. It could be a giant function.
I am afraid it is still subjective. You don't want to judge your design based on your ability to summarize a functionality with words. You always should be because this is how you pick method names and we all know naming is hard.
My advice is to see the SOLID principals as a whole instead of individual rules and build separation around what you think is going to change, and what is less likely to change. The obvious candidate being dependency. It is still going to be subjective, there is no way around that, but it'll help you.
I personally find it very difficult to do at times, but it is worth it. I don't know if you know Ecto which is an elixir project, but I had a "Voilà" moment when I've discovered it. It is not perfect is many ways, but the thing with Ecto and separation of concerns in general is that it seems a lot of indirections at first, but then the things are separated make sense. In its best blissful moments, it feels like a lot of small parts that you can trust.
I used to be in the position where it made sense to me that a model should be so smart that it knows how to save itself to the database, how to validates itself, how to do all sorts of things. But the reality is that as soon as you decide you want to work with another database, or validates differently depending on cases, etc, then it becomes hard to get your way out of this. I am sure some developer never felt this way and it is then fine. But for me it is a challenge.
Lots of simple cases, but you want each class to know as less as possible. You don't want your Mail class to know that the css colour for "urgent" is "#FF0000". And then harder ones like sometimes you don't even want it to know it is "urgent" because it depends on use case facts.
This is not easy. In you specific case, I personally would not bother mixing "create" and "delete" for example, but I would make sure interacting with the database is all it does. It does not know if the thing is valid, if it has callbacks, etc. Pretty much the Repository pattern. Again Ecto is a good example, or at least I find it helpful.
How does the SOLID "Interface Segregation Principle" differ from "Single Responsibility Principle"?
The Wikipedia entry for SOLID says that
ISP splits interfaces which are very large into smaller and more specific ones so that clients will only have to know about the methods that are of interest to them
However, to me that sounds like just applying the SRP to interfaces as well as classes. After all, if an interface is only responsible for just one conceptual thing, than you wouldn't be able to break it down further.
Am I missing something, or is ISP sort of redundant with SRP? If not, then what does ISP imply that SRP does not?
SRP tells us that you should only have a single responsibility in a module.
ISP tells us that you should not be forced to be confronted with more than you actually need. If you want to use a print() method from interface I, you shouldn't have to instantiate a SwimmingPool or a DriveThru class for that.
More concretely, and going straight to the point, they are different views on the same idea -- SRP is more focused on the designer-side point-of-view, while ISP is more focused on the client-side point-of-view. So you're basically right.
It all came from
The ISP was first used and formulated by Robert C. Martin when doing
some consulting for Xerox. Xerox had created a new printer system that
could perform a variety of tasks like stapling a set of printed papers
and faxing. The software for this system was created from the ground
up and performed its tasks successfully. As the software grew, making
modification became more and more difficult so that even the smallest
change would take a redeployment cycle to an hour. This was making it
near impossible to continue development. The design problem was that
one main Job class was used by almost all of the tasks. Anytime a
print job or a stapling job had to be done, a call was made to some
method in the Job class. This resulted in a huge or 'fat' class with
multitudes of methods specific to a variety of different clients.
Because of this design, a staple job would know about all the methods
of the print job, even though there was no use for them.
so
The solution suggested by Martin is what is called the Interface
Segregation Principle today. Applied to the Xerox software, a layer of
interfaces between the Job class and all of its clients was added
using the Dependency Inversion Principle. Instead of having one large
Job class, a Staple Job interface or a Print Job interface was created
that would be used by the Staple or Print classes, respectively,
calling methods of the Job class. Therefore, one interface was created
for each job, which were all implemented by the Job class.
# http://en.wikipedia.org/wiki/Interface_segregation_principle#Origin
SRP is concerned with what a module does, and how it is done, disallowing any mix of abstraction levels. Basically, as long as a component can be extensively defined with a single sentence, it will not break SRP.
On the other hand ISP is concerned with how a module should be consumed, whether it makes sense to consume just part of the module, while ignoring some aspect.
As an example of a code that keeps the spirit or SRP, but can break ISP is the Facade pattern. It has a single responsibility, "providing simplified access to a larger subsystem", but if the underlying subsystem needs to expose wildly different thinks, it does break ISP.
That said, usually when a piece of code breaks a SOLID principle, it often breaks the whole lot. Concrete examples that break a specific principle, while preserving the rest are rare in the wild.
Robert Martin tweeted the following on May 16, 2018.
ISP can be seen as similar to SRP for interfaces; but it is more than that. ISP generalizes into: “Don’t depend on more than you need.” SRP generalizes to “Gather together things that change for the same reasons and at the same times.”
Imagine a stack class with both push and pop. Imagine a client that only pushes. If that client depends upon the stack interface, it depends upon pop, which it does not need. SRP would not separate push from pop; ISP would.
SRP and ISP ultimately boils down to the same things. Implementing, either of them, needs a split of classes or interfaces.
However there are differences on other fronts.
Violation of SRP can have a far reaching effects on the entire design structure, giving rise to poor maintainability, reuse and of course low cohesion and coupling.
SRP has an impact on both the behavioral and structural components of an object structure.
Re designing on SRP violation needs a much deeper analysis, require looking at the different components of design in a holistic way.
Violation of ISP is mostly about poor readability ( and to some degree, low cohesion ). But the impact on maintenance and code re-use is far less sinister than SRP.
Moreover, refactoring code to ISP conformation, seems to be just a structural change.
See also my blog for SRP and ISP
From the point of my understanding, both principles are complementary, i.e. they need to be combined.
The ultimate consequence of violating ISP is becoming fragile, "shotgun surgury" or a "butterfly effect". A lot of code can break or require code updates because they depend onto some interface or objects which provide more than they needed. Changes become excessive.
The consequence of violating SRP is mainly decreased readability and maintentance. The lack of clear code structure may require people to search across the code base (a single responsibility is too distributed) or within a single large unit (multiple responsibilities scrammed together) to make a coherent change. In General, it is increased overhead to fully understand the concern (purpose) of some code snippet. Changes are prevented.
In that way, both principles act like a lower and upper bound for sane change management.
Examples for satisfying RSP without ISP – as provided by the other answers – express that there can be code which truly would belong together (like the stack example quote from Robert C. Martin). But it may do too much, is overengineered, etc. Maybe in very small examples, the effect is not visible, but if it grows large, it may be more comfortable to have a depending class still compile correctly after some unrelated part in the (indirect) dependency was changed. Rather than not compile anymore because unrelated things were changed.
In the SRP, a 'responsibility' is usually described as 'a reason to change', so that each class (or object?) should have only one reason someone should have to go in there and change it.
But if you take this to the extreme fine-grain you could say that an object adding two numbers together is a responsibility and a possible reason to change. Therefore the object should contain no other logic, because it would produce another reason for change.
I'm curious if there is anyone out there that has any strategies for 'scoping', the single-responsibility principle that's slightly less objective?
it comes down to the context of what you are modeling. I've done some extensive writing and presenting on the SOLID principles and I specifically address your question in my discussions of Single Responsibility.
The following first appeared in the Jan/Feb 2010 issue of Code Magazine, and is available online at "S.O.L.I.D. Software Development, One Step at a Time"
The Single Responsibility Principle
says that a class should have one, and
only one, reason to change.
This may seem counter-intuitive at
first. Wouldn’t it be easier to say
that a class should only have one
reason to exist? Actually, no-one
reason to exist could very easily be
taken to an extreme that would cause
more harm than good. If you take it to
that extreme and build classes that
have one reason to exist, you may end
up with only one method per class.
This would cause a large sprawl of
classes for even the most simple of
processes, causing the system to be
difficult to understand and difficult
to change.
The reason that a class should have
one reason to change, instead of one
reason to exist, is the business
context in which you are building the
system. Even if two concepts are
logically different, the business
context in which they are needed may
necessitate them becoming one and the
same. The key point of deciding when a
class should change is not based on a
purely logical separation of concepts,
but rather the business’s perception
of the concept. When the business
perception and context has changed,
then you have a reason to change the
class. To understand what
responsibilities a single class should
have, you need to first understand
what concept should be encapsulated by
that class and where you expect the
implementation details of that concept
to change.
Consider an engine in a car, for
example. Do you care about the inner
working of the engine? Do you care
that you have a specific size of
piston, camshaft, fuel injector, etc?
Or, do you only care that the engine
operates as expected when you get in
the car? The answer, of course,
depends entirely on the context in
which you need to use the engine.
If you are a mechanic working in an
auto shop, you probably care about the
inner workings of the engine. You need
to know the specific model, the
various part sizes, and other
specifications of the engine. If you
don’t have this information available,
you likely cannot service the engine
appropriately. However, if you are an
average everyday person that only
needs transportation from point A to
point B, you will likely not need that
level of information. The notion of
the individual pistons, spark plugs,
pulleys, belts, etc., is almost
meaningless to you. You only care that
the car you are driving has an engine
and that it performs correctly.
The engine example drives straight to
the heart of the Single Responsibility
Principle. The contexts of driving the
car vs. servicing the engine provide
two different notions of what should
and should not be a single concept-a
reason for change. In the context of
servicing the engine, every individual
part needs to be separate. You need to
code them as single classes and ensure
they are all up to their individual
specifications. In the context of
driving a car, though, the engine is a
single concept that does not need to
be broken down any further. You would
likely have a single class called
Engine, in this case. In either case,
the context has determined what the
appropriate separation of
responsibilities is.
I tend to think in term of "velocity of change" of the business requirements rather than "reason to change" .
The question is indeed how likely stuffs will change together, not whether they could change or not.
The difference is subtle, but helps me. Let's consider the example on wikipedia about the reporting engine:
if the likelihood that the content and the template of the report change at the same time is high, it can be one component because they are apparently related. (It can also be two)
but if the likelihood that the content change without the template is important, then it must be two components, because they are not related. (Would be dangerous to have one)
But I know that's a personal interpretation of the SRP.
Also, a second technique that I like is: "Describe your class in one sentence". It usually helps me to identify if there is a clear responsibility or not.
I don't see performing a task like adding two numbers together as a responsibility. Responsibilities come in different shapes and sizes but they certainly should be seen as something larger than performing a single function.
To understand this better, it is probably helpful to clearly differentiate between what a class is responsible for and what a method does. A method should "do only one thing" (e.g. add two numbers, though for most purposes '+' is a method that does that already) while a class should present a single clear "responsibility" to it's consumers. It's responsibility is at a much higher level than a method.
A class like Repository has a clear and singular responsibility. It has multiple methods like Save and Load, but a clear responsibility to provide persistence support for Person entities. A class may also co-ordinate and/or abstract the responsibilities of dependent classes, again presenting this as a single responsibility to other consuming classes.
The bottom line is if the application of SRP is leading to single-method classes who's whole purpose seems to be just to wrap the functionality of that method in a class then SRP is not being applied correctly.
A simple rule of thumb I use is that: the level or grainularity of responsibility should match the level or grainularity of the "entity" in question. Obviously the purpose of a method will always be more precise than that of a class, or service, or component.
A good strategiy for evaluating the level of responsibility can be to use an appropriate metaphor. If you can relate what you are doing to something that exists in the real world it can help give you another view of the problem you're trying to solve - including being able to identify appropriate levels of abstraction and responsibility.
#Derick bailey: nice explanation
Some additions: It is totally acceptable that application of SRP is contextual base.
The question still remains: are there any objective ways to define if a given class violates SRP ?
Some design contexts are quite obvious ( like the car example by Derick ) but otherwise contexts in which a class's behaviour has to defined remains fuzzy many-a-times.
For such cases, it might well be helpful if the fuzzy class behaviour is analysed by splitting it's responsibilities into different classes and then measuring the impact of new behavioural and structural relations that has emanated because of the split.
As soon the split is done, the reasons to keep the splitted responsibilities or to back-merge them into single responsibility becomes obvious at once.
I have applied this approach and which has lead good results for me.
But my search to look for 'objective ways of defining a class responsibility' still continues.
I respectful don't agree when Chris Nicola's above says that "a class should presents a single clear "responsibility" to it's consumers
I think SRP is about having a good design inside the class, not class' customers.
To me it's not very clear what a responsability is, and the prove is the number of questions that this concept arises.
"single reason to change"
or
"if the description contains the word
"and" then it needs to be split"
leads to the question: where is the limit? At the end, any class with 2 public methods has 2 reasons to change, isn't it?
For me, the true SRP leads to the Facade pattern, where you have a class that simply delegades the calls to other classes
For example:
class Modem
send()
receive()
Refactors to ==>
class ModemSender
class ModelReceiver
+
class Modem
send() -> ModemSender.send()
receive() -> ModemReceiver.receive()
Opinions are wellcome
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?
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.
Write a brief, but accurate description of what the class does.
If the description contains the word "and" then it needs to be split.
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, and verify financial records... Why would you want a single object to do all these? (it's okay if a class takes on multiple responsibilities as long as they are all related and coherent.)
If you employ a CRC card, it's a nice subtle guideline. If you're having trouble getting all the responsibilities of that object on a CRC card, it's 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.
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.
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 don't have a good single responsibility.
Often it's hard to initially find responsibilities, and 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 it's because you are mixing an abstract and concrete concept together. They tend to be harder to see, and, again, use in different contexts will help clarify.
The obvious sign is when your class ends up looking like a Big Ball of Mud, which is really the opposite of SRP (single responsibility principle).
Basically, all the object's services should be focused on carrying out a single responsibility, meaning every time your class changes and adds a service which does not respect that, you know you're "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.
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.
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.
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.
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.
I've also been trying to get my head around the SOLID principles of OOD, specifically the single responsibility principle, aka SRP (as a side note the podcast with Jeff Atwood, Joel Spolsky and "Uncle Bob" is worth a listen). The big question for me is: What problems is SOLID trying to address?
OOP is all about modeling. The main purpose of modeling is to present a problem in a way that allows us to understand it and solve it. Modeling forces us to focus on the important details. At the same time we can use encapsulation to hide the "unimportant" details so that we only have to deal with them when absolutely necessary.
I guess you should ask yourself: What problem is your class trying to solve? Has the important information you need to solve this problem risen to the surface? Are the unimportant details tucked away so that you only have to think about them when absolutely necessary?
Thinking about these things results in programs that are easier to understand, maintain and extend. I think this is at the heart of OOD and the SOLID principles, including SRP.
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. :)
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...