E
E
ettaluni2021-09-16 23:07:17
Programming
ettaluni, 2021-09-16 23:07:17

Multiple if then else, how to replace, simplify and forgive?

How do you solve multiple if then else? In any language.
Here you have a situation for each of the 85 subjects of the Russian Federation to perform its action. What will you do? Unwind a footcloth?
The option with switch is of little interest because of the similar block structure.

Answer the question

In order to leave comments, you need to log in

5 answer(s)
D
Developer, 2021-09-16
@samodum

Strategy pattern.
Or reflection.
Or HashMap.
Or Dictionary.
Or switch... case
Depending on the details of the task.

V
Vladimir Kuts, 2021-09-16
@fox_12

Well, in python, for example, you can solve this

# некий набор функций для каждого региона
def region1():
    ....

def region2():
     ...

def defaultregion():
    ...

# соответствие номеров функциям
func = {
   '1': region1,
   '2': region2,
   ...
}.get(region_number, defaultregion)

func()   # в func - нужная функция, обусловленная выбором номера региона. выполняем ее

A
Adamos, 2021-09-16
@Adamos

If there is only one simple action for each - either a switch, or a table in general.
The size of the footcloth, by and large, is unimportant - readability and obviousness are important, especially when changes are made.
More complex cases depend on the language. You can make patterns or cool inheritance in many languages, but this will not be read everywhere, and in some places such a solution will create problems at the first edit ... a footcloth is better, but simple as a footcloth.

G
GavriKos, 2021-09-16
@GavriKos

Dictionary \ associative array \ map (well, and other variants of the key-value collection), where the key is the subject, the value is the action.
It remains only to briefly fill in, here to help the means of a language such as reflection, attributes (for example).

S
Saboteur, 2021-09-16
@saboteur_kiev

executor pattern something like:
array { id, name, function}
[ 0, 'object1', 'function1' ],
[ 1, 'object2', 'function2'],
[3, 'object3', 'function1;function3 ']
while ID in array(id) {
eval array(function)
}
or switch/case

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question