Skip to content

re: SLAP Your Functions! VIEW POST


Just extracting a commented part of a function into another one does not help to make it more readable, because now, to understand what it does, you have to jump around in your code. This mental contrxt switch makes it harder to read actually.

Of course you should avoid long functions. But do this by abstracting the problem, not the implementation!


This mental context switch makes it harder to read actually.

Maybe, maybe not ...


def tweet_to_html(tweet):
   res = re.sub(r"(^|\s)@(\w+)",
                r'\1<span class="handle">@\2</span>'
   res = "<pre>" + res + "</pre>"
   return res


def tweet_to_html(tweet):
    res = insert_span_around_handles(tweet)
    res = surround_with_pre(res)
    return res

I find the second version much easier to understand :)


the first could be written:

def tweet_to_html(tweet):
    //insert span around handle
    res = ...

Here the function is nothing more than specifying a name, you can do this in a comment

If you just add a comment, you still have to skim past all the implementation details to figure out what the function is intending to do. With this example this, since it's such a small function this isn't too burdensome but if the implementation is more complex, then that's a lot of noise to sift through to determine what the function does.

code of conduct - report abuse