vendredi 14 septembre 2018

Replace multiple conditions with DRY solution

I have A: boolean; B: boolean;

A=0, B=0: run func1 and func2
A=0, B=1: run func1 and func3
A=1, B=0: run func2
A=1, B=1: run func3

Every function has different signatures with a different number of arguments.
Right now i did something like this:

if not A and not B: run func1 and func2
if not A and B: run func1 and func2
if A and not B: run func1 and func2
if A and B: run func1 and func2

but instead of calling functions i repeat the same code block for every if statement, i know it's redundant, how can i replace this massive block of if statements into a few line of code calling the right method only once when necessary?

I thought that i could use a mapping Dictionary like this:

mapping_dict = {
    True: {
        True: [func3],
        False: [func2]
    },
    False: {
        True: [func1, func3],
        False: [func1, func2]
    }

but even so, i need a solution to determine which arguments to pass the function depending on the function returned by

mapping_dict[A][B]

Mine could be a specific case but i would like to know how to approach this kind of problems with a "Don't Repeat Yourself" solution, is there any pattern for this problem? how does it work? Is it language-indipendent?

Thank you for your patience

Aucun commentaire:

Enregistrer un commentaire