dimanche 15 décembre 2019

Is there a better alternative to check for collections with members with optional interfaces?

I have a configuration registry class which holds a collection of configuration classes with a certain interface. These classes can also have an optional interface. So these classes may look like this in pseudocode:

class ConfigurationRegistry {   
    private ModuleConfiguration[];

    public function ConfigurationRegistry(ModuleConfiguration[] collection) {
       this.collection = collection;
    }

    public function getCollection() {
       return this.collection;
    }
}
class ConfigurationClass1 implements ModuleConfiguration, SpecificConfiguration {
    public function moduleMethod() {
       // do something
    }    

    public function specificMethod() {
       // do specific thing
    }
}
class ConfigurationClass2 implements ModuleConfiguration {
    public function moduleMethod() {
       // do something
    }    
}
public interface ModuleConfiguration {
    public function moduleMethod();
}
public interface SpecificConfiguration {
    public function specificMethod();
}

In my client code I would like to use these configuration classes. Sometimes I need the whole collection of configuration classes and sometimes I only need to collection of configuration classes which implement the SpecificConfiguration interface.

I could filter the collection method by using instanceof or I could loop through the collection and check whether the class implements the interface. But I've read quite a few articles stating online that using instanceof in this case is not considered a good practice.

My question is: is my implementation a good design? If not, do you have any suggestions how I could redesign or improve this?

Aucun commentaire:

Enregistrer un commentaire