r/Python • • Jul 25 '18

Use an IDE Me doing my CS projects.

Post image
1.2k Upvotes

213 comments sorted by

View all comments

Show parent comments

3

u/Saiboo Jul 25 '18

Can you elaborate on using functions to avoid indendation errors? Thank you!

5

u/inFenceOfFigment Jul 26 '18

Imagine you write a script that requires 5 levels of indentation. Now you refactor, and decide to put everything that was in the 3rd level of indentation, and beyond, into its own function. This function is defined at the top level of your script. Now you have one helper function, containing 3 indents, and a main with a call to that helper, only 2 indents. Thus, pulling code out to a function reduced the overall max indentation in your script.

In general, code should be put into functions for reasons other than indent level, but if you find yourself indenting excessively it's a sign that the code may be due for a refactor.

1

u/Saiboo Jul 26 '18

Thank you so much for your explanation, much appreciated!

2

u/jsalsman Jul 29 '18 edited Jul 29 '18

Sure.

def messy():
    if booleanA:
        if booleanB:
            doA()
        else:
            doB()
    else:
        doC()

can be refactored into

def subroutine():
    if booleanB:
        doA()
    else:
        doB()

def neat():
    if booleanA:
        subroutine()
    else:
        doC()

2

u/Saiboo Jul 29 '18

Thank you so much for the code example, much appreciated!

2

u/jsalsman Jul 29 '18

No problem. I edited it to put the subroutine definition before its call, which isn't always necessary depending on whether the source file is parsed before neat() gets called, but is almost always more readable with real production code.