DEV Community

Discussion on: Single-Responsibility Principle done right

Collapse
orkon profile image
Alex Rudenko

I think SRP might be more easily interpreted when applied to functions, not classes. With functions, it's easier to say what it is responsible for because a function is not a collection of attributes and methods like a class. Also, a class is expected to correspond to some domain concepts which may not follow SRP themselves. I think Yegor's example does not need classes at all: one can have just three functions which all follow SRP: exists, read and write (pretty much like corresponding POSIX system calls). Also, the Yegor's example is quite similar to Martin's example, and I am not convinced that the following conclusion is true:

The classes ExistenceChecker, ContentReader, and ContentWriter will probably always be used together.

Some clients might only want to read the data, others just write. The existence check might not be used at all. I notice the same patterns used in Java. For example, docs.oracle.com/javase/7/docs/api/... & docs.oracle.com/javase/7/docs/api/... and tons of other classes are split into readers and writers.

P.S. is it a good thing when a Rectangle draws itself using a draw method? Should not some other thing draw a rectangle? I noticed that this kind of patterns is often confusing to people new to OOP.

Collapse
courier10pt profile image
Bob van Hoove • Edited on

Some clients might only want to read the data, others just write.

OP:

the clients of a class define if it fulfills or not the principle.

Seems like you're on the same page.

Collapse
riccardo_cardin profile image
Riccardo Cardin Author

Well, talking about functional programming, your reasoning is correct. But, here we are talking about object-oriented programming ;)

Anyway, if clients of reading and write operations are different, then the design should be reviewed. In this fact, I agree with you.

Collapse
alainvanhout profile image
Alain Van Hout • Edited on

I've always found it counterintuitive that a square should be able to draw itself. What if you don't use a method of drawing that was known when the Rectangle class was created? (assuming perfect foresight is a big OOP issue -- and decorators and visitors aren't a panacea)