dimanche 5 janvier 2020

Are "optional interfaces" considered a bad practice?

Let's say I have a list of objects which may or may not implement a certain interface. I would like to split this list into a few different lists with 1 list containing the objects which do implement the interface and another list containing the objects which do not have the interface.

I could do this by using "instanceof", but I've read online that using "instanceof" is generally considered bad practice. Is there a better way to achieve what I want?

My use case: I want to have configuration objects which may or may not implement an interface. This interface should be implemented when you'd like to configure those values.

<?php

interface OptionalInterface {
    public function method1();
    public function method2();
}

class A implements OptionalInterface {
    public function method1() {}
    public function method2() {}
}

class B implements OptionalInterface {
    public function method1() {}
    public function method2() {}
}

class C {

}

class Application {
    public function main()
    {
        $classes = [
            new A(),
            new B(),
            new C()
        ];

        $nonInterfaceArray = [];
        $interfaceAray = [];

        foreach($classes as $class) {
            if ($classes instanceof OptionalInterface) {
                $interfaceAray[] = $class;
            } else {
                $nonInterfaceArray[] = $class;
            }
        }

    }
}

Aucun commentaire:

Enregistrer un commentaire