Search code examples
phpclasssingle-responsibility-principle

Single-responsability principle


Let's say you have abstract class A doing some stuff. Then you have abstract class B doing other stuff.

And lastly a few normal classes, let's say C ... Z.

Both A and B provide functionality that are used by class C .. Z classes. In my case mainly an observer pattern which is static, and some __get magic + lazy-loading for a certain type of properties - this is not static. I'm thinking to merge this into one class, but then I'm sure it violates SRP :)

So I am extending A, B in C, D etc... Essentially all C .. Z classes inherit the functionality of the A & B classes. So besides what they are supposed to do, they also do the observer stuff and so on

Does this violate the single-responsability principle?


Solution

  • I don't know if this applies to your specific case, but I find that most of the time, an abstract class and its implementation can be split into two normal classes.

    For example:

    abstract class AbstractAdder {
        int AddThree(int a) {
            Add(a, 3);
        }
    
        abstract int Add(int a, int b);
    }
    
    class NormalAdder inherits AbstractAdder {
        int Add(int a, int b) {
            return a + b;
        }
    }
    
    var result = new NormalAdder().AddThree(6);
    

    Can be changed into:

    class ThreeAdder {
        ThreeAdder(IGenericAdder genericAdder) {
            this.genericAdder = genericAdder;
        }
    
        int AddThree(int a) {
            return this.genericAdder.Add(a, 3);
        }
    }
    
    class NormalAdder implements IGenericAdder {
        int Add(int a, int b) {
            return a + b;
        }
    }
    
    var result = new ThreeAdder(new NormalAdder()).AddThree(6);
    

    This has several advantages:

    • The classes are less tightly coupled, because they don't inherit from each other. Because the classes are separate, the responsibilities are more separate and well-defined.
    • You can use functionality of multiple classes, whereas you can only inherit from one abstract class. (Edit: apparently not in PHP because you have multiple inheritance)
    • It is clearer (IMHO) on which class the method is called.

    It seems like you are using inheritance to couple multiple classes, but that is not what inheritance is meant for.