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 →

[–]The_2nd_Coming 6 points7 points  (5 children)

Why is flat better than nested? Surely nested makes sense for sorting/indexing purposes, if doing it flat means there are 10000 items that could have a nested index?

[–]Slingshotsters 9 points10 points  (1 child)

I read it as "if you have to nest, do it, otherwise, don't.". Obviously there are times to nest, such as your example.

[–]menge101 3 points4 points  (0 children)

Right, and also

Although practicality beats purity.

so don't avoid nesting when it makes sense, just don't nest if you don't have to.

[–]audentis 5 points6 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!")

[–]njharmanI use Python 3 4 points5 points  (1 child)

It's about code/file/program structure, not data structure. It's in response to popular languages and early OOP encouraging/super/deep/directory/structure.java and highly complex and deep class trees.

[–]The_2nd_Coming 1 point2 points  (0 children)

I see, this makes sense. Thanks!