mardi 26 septembre 2017

Nested switches or multiple functions, what would be a better design?

I have a large method that looks something like this

void operate(Provider provider, Method method) {
    switch (provider) {
        case PROVIDER_1:
            //TODO Do common things to provider 1
            switch (method) {
                case METHOD_1:
                    break;
                case METHOD_2:
                    break;
                case METHOD_3:
                    break;
            }
            break;
        case PROVIDER_2:
            switch (method) {
                case METHOD_1:
                    break;
                case METHOD_2:
                    break;
                case METHOD_3:
                    break;
            }
            break;
    }

So each time I need to add a provider I'll need to add a case to that provider and then repeat the method switch for this new provider.

I got a suggestion from a fellow that should be split into methods for each method so for example instead of the above, it'll be

void operateByMethod1(Provider provider) {
    switch (provider) {
        case PROVIDER_1:
            //TODO Do common things to provider 1
            break;
        case PROVIDER_2:
            break;
    }

void operateByMethod2(Provider provider) {
    switch (provider) {
        case PROVIDER_1:
            //TODO Do common things to provider 1
            break;
        case PROVIDER_2:
            break;
    }

void operateByMethod3(Provider provider) {
    switch (provider) {
        case PROVIDER_1:
            //TODO Do common things to provider 1
            break;
        case PROVIDER_2:
            break;
    }


Personal thoughts: Maybe splitting into multiple methods makes it more cleaner but if I need to do common stuff to PROVIDER_1 (despite the method) then this common thing will need to be repeated/duplicated in each method (as indicated by the //TODOs in the above code) which kinda means more lines of code but that's a bit irrelevant maybe.

I'd like to hear some thoughts about this, which would you consider more readable and more clean? Any better alternatives?

Aucun commentaire:

Enregistrer un commentaire