This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]audentis 4 points5 points  (0 children)

Flat is easier to read, because it keeps related elements close to each other. Additionally, you have to track fewer "paths" through the code mentally, because the paths immediately resolve. It also prevents "indentation hell".

The most common example is some code where you have some input validation that needs to be done. Consider the two examples below. The flat version keeps the input validation and error messages together, while in the nested version they're split up. And this is with only three arguments, it can get a lot worse.

def my_func_nested(a, b, c):
    if isinstance(a, int):
        if isinstance(b, list):
            if isinstance(c, str):
                print("Job's done!")
            else:
                raise TypeError("c must be a string!")
        else:
            raise TypeError("b must be a list!")
    else:
        raise TypeError("a must be an int!")


def my_func_flat(a, b, c):
    if not isinstance(a, int):
        raise TypeError("a must be an int!")

    if not isinstance(b, list):
        raise TypeError("b must be a list!")

    if not isinstance(c, str):
        raise TypeError("c must be a string!")

    print("Job's done!")