dimanche 17 février 2019

Is it making sense to replace complex conditional statements with Strategy pattern in this case

I have a value which needs to be returned from a method only if certain conditions are satisfied otherwise I have to return null.
That method is getting 2 boolean parameters based on which further methods are called to check some other conditions.

Call method1, then method2 -> if (param1 && param2) == true;
Don't call any method-> if (!param1 && !param2) == true;
Call only method1 -> if only param1 == true;
Call only method2 -> if only param2 == true; //Method2 is an expensive operation.

So, to meet this requirement, I wrote a code which looks like this -

value = doSomeProcessingToGetValue(); //Not an expensive operation
if(param1 && param2) //both are true {
    if(method1() != null) { // if method1 return true then move ahead
        if(method2() != null) { //if method2 return true then move ahead (Expensive operation)
            return value; //Means all the conditions are satisfied now
        }
    }
}
else if(!param1 && !param2) //both are false {
    return value; //No need to check for any condition
}
else if(param1) //Means param1 is true {
    if(method1()!=null) {// if method1 return true then move ahead
        return value; //Means all the conditions are satisfied now
    }
}
else { //Means param2 is true
    if(method2()!=null) {// if method2 return true then move ahead(Expensive operation)
        return value; //Means all the conditions are satisfied now
    }
}
return null;

I have 2 concerns with above approach -

Scalability - This solution is not scalable because in future some more parameters may need to be checked with their respective methods to be called. So, the no. of if else checks will increase exponentially with addition of each parameter.
Not Elegant - Since there are too many conditional checks, it's not looking very elegant. To make it more elegant, I am thinking of applying Strategy pattern.
Strategy pattern approach Speaking about high level, I will create concrete classes for each if condition given above. So, for above code, there will be four concrete classes. I will loop over all the concrete classes & will check if any of them satisfies the conditions & will return the value accordingly.
My query is does it make sense to use strategy pattern to satisfy this requirement since this solution also performs poorly in terms of scalability.
Or Can there be any better approach which will be good in terms of scalability.

Aucun commentaire:

Enregistrer un commentaire