Question

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?

Was it helpful?

Solution

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.

OTHER TIPS

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.

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