mercredi 18 août 2021

how to rewrite this code to avoid switches/casting

Simplified example to give you an idea, hope it's be clear.
I've already added inheritance for Service class to avoid switches I'm having now

class Config {}

class ConfigA extends Config {}
class ConfigB extends Config {}

// service class - different implementation for configA and ConfigB
// normally it would look like
class ServiceA {
    public String run(ConfigA configA) {}
}

thus next then I need sth like

class ServiceRunner {
    public String run(Config config) {
        // if or switch doesn't matter now
        if (config  instanceof ConfigA) {
            return serviceA.run((ConfigA)config);
        }
    }
}

// main
Config config =  configFactory.create(...) // returns ConfigA or ConfigB
String result = serviceRunner.run(config);

Is there a better way to code it I mean without casting? The only solution I can see is:

interface Service { String run(); }

@RequestScope
class ServiceA implements Service {
    private ConfigA  config;
    public ServiceA(ConfigA configA) {this.configA = configA}

    public String run() {
        ...
    }
}

but I'm not convinced it's a good idea to implement service beans as state beans and I'm using CDI (quarkus actually) for DI which it seems doesn't support assisted injection via constructor

Aucun commentaire:

Enregistrer un commentaire