5

This question already has an answer here:

Single responsibility (from SOLID) is like making me create classes with only one public method. But if it's so, it would be possible use static methods, and go back to procedural programming. What's the difference?

marked as duplicate by gnat, GlenH7, user40980, Arseni Mourzenko, Dan Pichelman Mar 11 '15 at 1:49

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4

Single responsibility (from SOLID) is like making me create classes with only one public method.

Then you're doing it wrong or need to use a language with good delegate/functor/function object support. Very few responsibilities can be represented with a single pure function.

In languages like Java this can happen because you need to use interfaces to provide different implementations to a single function interface, but in general this should not happen. Certainly you can make everything static functions that just pass data around, and if that's easier, by all means do procedural or functional programming.

But for many problems, having some shared state or some protected invariants make your life easier, and OO does that work well.

6

The single responsibility principle doesn't force you to have classes with only one public method. It just states that a class should do one thing, and it should do it well.

For example, a GraphNode could contain public functions to print a description, to rename the node or to rearrange it within its canvas... However, everything related to the edges would be better placed in its own GraphEdge class, even though it might seems that a "few additional edge methods shouldn't disturb anyone."

Another good indicator for classes that commonly violate the SRP are XYZHelpers or ABCManagers classes which oftentimes implement a bunch of different methods that are only remotely related to each other. In most cases, these methods should be re-factored and belong to a specific class, (or a new classes) depending on the scenario.

However, I believe that all patterns, principles and best practices should always be taken with a grain of salt. Although they are unbelievably helpful, blindly applying them without using common sense might do you more harm than good.

  • No, this isn't true at all. The canonical definition of SRP (as defined by Uncle Bob) is that things should have a single reason to change. A class can do several things, as long as it's impossible for one change in business requirements to require SOME of those things be changed, but not others. What you are describing is called cohesion – sara Jun 30 '16 at 11:01

Not the answer you're looking for? Browse other questions tagged or ask your own question.