Search code examples
phpoopmaintainabilitydefensive-programming

Force classes to implement one of a set of methods


Let's say I need a group of classes to implement all of methods X, Y and Z to work properly. In that case, I can let them implement a common interface to force that.

Now, my case is a bit different - my classes need to implement at least one of X, Y and Z, not necessarily all of them. Interfaces can't help me here. The closest thing I can think of is a common parent - it can check the existence of X, Y or Z in its construcor.

I'd rather avoid inheritance here, because I may need to implement this "interface" in a class that already has a parent. So - is there another elegant way to do this?

(I am working in PHP, but if a general OOP solution exists, it may serve to a broader audience.)


Solution

  • I'd rather avoid inheritance here, because I may need to implement this "interface" in a class that already has a parent. So - is there another elegant way to do this?

    If I understood you correctly, you can solve that issue through Traits:

    trait DefaultImpl
    {
        public function x()
        {
            echo "Default implementation of x()\n";
        }
    
        public function y()
        {
            echo "Default implementation of y()\n";
        }
    
        public function z()
        {
            echo "Default implementation of z()\n";
        }
    }
    
    class XImpl
    {
        use DefaultImpl;
    
        public function x()
        {
            echo "Custom implementation of X\n";
        }
    }
    
    $x = new XImpl();
    $x->x();
    $x->y();
    $x->z();
    

    It's not a very good solution from design point of view. But it's better than unnecessary inheritance.