Hacker News new | ask | show | jobs
by pfranz 2732 days ago
Isn't deep nesting (hence deep indentation) a sign of code smell? Yeah, you might end up shuffling the logic into a new file or a function that makes the file much longer, but I've noticed when doing that kind of refactoring it forces you to clean up the scoping quite a bit so there's less state to keep track of.
1 comments

It depends on your definition of "deep".

Imagine an if, inside of a foreach, inside of a function definition, inside of a class. This is not terrible code, it's perfectly reasonable.

Now you're indented four levels in. Now combine this with some rather unreasonable and outdated assumptions that PEP8 (automatically enforced in many shops and OSS projects) has, like pretending that people are still on glass terminals and that anything longer than 79 characters is a problem. It also insists on four-space tabs, so this very simple construct has eaten 20% of your line budget.

..not to mention how it makes your code harder to read. I also share the author's concern about how you're less able to separate your debug code from your actual code.

This is all subjective, so it's hard to make a water-tight argument either way (even if we were looking at a concrete code example)...that's one reason it's referred to as "smell" instead of a bad-practice. PEP-8 effectively starts with "A Foolish Consistency is the Hobgoblin of Little Minds." Every place I've worked used a modified version of PEP-8 for standards because it never worked out of the box. Like I was saying higher up, it's hard to tell who to blame. It is the reality of using that language, but the developers have made a strong effort to address it. I guess it's a lesson to future language designers or community managers?

More concretely, I often find deeply indented code more difficult to read. There are more local variables to keep track of and breaking it out into a function helps encapsulate and name what's going on. Even from your description I might look to see if I could use a generator to filter the loop instead of "for" and "if" which should be more clear, fewer indentations, and easier to optimize at runtime. I do find trying to break up long line onto multiple rather annoying because diffs are more difficult to read.

I've never really used whitespace to separate my debug and actual code...which probably speaks more to my background than anything else. I have tended to put a # at the beginning of the line when debugging and next to the comment when commenting. Linters don't seem to care for that, but the code is tidied up before it's committed.

Four-space indent is very common in other languages too. I don't see why this choice should be argued over for Python specifically. The 80 char limit is also very common.

I too used to leave debug-code purposefully unindented. There are other ways to handle that and the loss is negligible to me considering there can't be misplaced braces in Python in return.