Story of a snippet: how to avoid complicated “IF” statements

Posted on Posted in Snippets

book-and-candle

Today we want to focus on the very nice snippet proposed by our user Miklós Prisznyák (mprisznyak): “how to avoid complicated “IF” statements”. The snippet code is available at the following link.

As you can see, Miklós provides an effective and good programming technique example to avoid too many nested and complicated “IF” statements. In a typical “IF-THEN-ELSE” scenario, with many possible conditions to test, you may think to indicate all the conditions as a sequence of nested ‘IF’ statements. For each statement you might test the condition, returning “true” when the condition is correct, like in the example below.

This is not the best possible solution. In fact, because of the number of boolean statements, you may have a lot of exiting points, which make the code hard to be read and maintained. This is definitely an ugly programming style, we can do better! 🙂

Starting from this point, we can improve our code by replacing each “IF” statement with a function, returning true or false, depending on its own logic. Note that each function can define another function inside itself, to wrap the logic of nested IFs… very pythonic, very functional programming, isn’t it?

Here the code..

Once the functions are defined, we need to find a simple way to invoke them till one of the conditions is verified. This is done using the python built-in locals().items() function, which returns the key-value pairs of local variables in a list. (To learn more on this, please read the Python Official Documentation).

In this case we can use such list to access the functions defined in the code (which name starts with ‘decision’) and easily execute them, iterating the list. When the condition is verified we can use the “BREAK” statement to terminate the loop. We can handle the case where no method returns true using the “LOOP/ELSE” statement, returning false.

Finally we can define the main and test our code…

Have fun with this good and nice-to-see example of functional python programming, Thanks Miklós!

Leave a Reply

Your email address will not be published. Required fields are marked *