Answer the question
In order to leave comments, you need to log in
How to get rid of multiple if/else?
Good day!
There is something like this pseudo-code for some calculations:
IF Условие 1 THEN
Делаем расчеты первым методом
ELSE IF Условие 2 THEN
Делаем расчеты вторым методом
ELSE IF Условие 3 THEN
Делаем расчеты третьим методом
ELSE
Здесь обращаемся к базе данных и находим последнее валидное значение
END
Answer the question
In order to leave comments, you need to log in
class CalculationData;
abstract class Calculation
{
public function calculate(CalculationData data);
}
class CalculationQueue
{
public function addCalculation(Calculation calculationVariant, int priority);
public function calculate(CalculationData data) {
for (c in calculations) {
if(res = c.calculate(data)) return res;
}
}
}
Usually, a blanket of conditional expressions (especially multi-level ones) is a signal that you can use the state pattern . It is also useful to decompose the code that makes the decision and the code that performs the calculation, that is, return not the result of the calculations, but the behavior that performs them . It's nice to wrap it in a maybe-type so that the calling code can delegate getting the default value to other code.
Let's choose the first method for this, if it didn't work out first, then you need to try the second, otherwise try the third, but if all the methods did not bring successful results, then you need to contact the Database and find the last successful value there.Your code does not match this description. In the above if-else chain, the execution of a method depends not on the result of the previous method, but on a set of certain external conditions. For a chain, you can use
result = tryMethod1() || tryMethod2() || ... || getFromDB();
it all depends on how the conditions are arranged and the actions performed.
Without this specificity, there can be no answer, except for the obvious switch
here it depends on what kind of conditions
if the condition is a comparison with a constant, and there are a lot of such conditions, I would use a dictionary (associative array) in the values \u200b\u200bof which there would be pointers to a function
, if the conditions themselves are some kind of calculations, then of course you can’t do without enumeration .
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question