Search code examples
inheritanceinterfacesingle-responsibility-principle

How to not violate Single Responsibility Principle?


I am new to programming and I am learning design things.

I was taught that SRP is super important such that every class should have one responsibility. Thus, I wanted to inherit responsibilities from other classes. But then, I realized java doesn't allow multiple inheritances, but only interfaces. I think the problem of implementing multiple interfaces is that you have to write the methods inside the one class that implements the interfaces anyways. So you have to go to the class that implements the interface to fix the method. Then isn't it considered to violated SRP?

In short, I want a class A, say dog, that construct a thing and need methods B(bark), C(eat), and D(sleep) about the A. How do I do that without violating SRP?


Solution

  • SRP is commonly stated as "Every class should have one responsibility," but this is inaccurate. A better statement is, "A module should have one and only one reason to change." As I describe in Single Responsibility Principle: Is It a Fundamental Mistake? I can think of two possible axes of change:

    1. Business change
    2. Technological change

    To reduce business change to "one reason to change" means there should only be one person in the business who asks you to change a particular module. For example, some of the people who might ask for a change are the head of product, or the head of design. So this means we should separate how a thing behaves from how it looks.

    An example of technological change is changing how a thing is stored. "We need to change from an SQL database to flat NoSQL storage."

    So what it does, how it looks, infrastructure it depends on — these are things that should be separated. Not your Dog. The Interface Segregation Principle leads to thin slices of interfaces, like Barking and Eating. This enables callers to depend on these thin slices, instead of on some huge interface like Animal that has lots of things it doesn't need.

    So I'd say

    class Dog: Barking & Eating & Sleeping
    

    doesn't necessarily violate SRP, especially when each interface is thin.

    That said, I've seen people slap unrelated interfaces together to create monstrosities. It's mainly a result of lazily using an existing class as a dumping ground. As long as you keep asking, "Can this be separated?" and seeing if you can extract responsibilities, you're doing better than most people.