I like comments, probably too much. Lately I’ve been rethinking some comments because they just don’t make sense or work in the real world. But not till I watched this video did I realize you could change them into code.
Make A Comment Into a Variable.
Variable names – good variable names – are self commenting. Extreme Programming uses the phrase “Destroy All Comments”.
Example:
# is window too tall if window.height > 100: fix_window_height()
Becomes:
IsWindowTooTall = window.height > 100 if IsWindowTooTall: fix_window_height()
Example:
widget.reset(True) # forces re-draw
becomes:
force_redraw = True widget.reset(force_redraw)
Also makes it easier to put in debugging code later because you already have a name for the value to print. True is also a magic number in a sense because we don’t know what it means.
Make Code Section Comments Into Functions
Example:
# open the barn barn = code.Barn.get() barn.unlock() barn.open() # saddle the horse saddle = code.Saddle.get() saddle.install(horse)
Becomes:
open_barn() saddle(horse) def open_barn(): barn = code.Barn.get() barn.unlock() barn.open() def saddle(horse): saddle = code.Saddle.get() saddle.install(horse)
I once asked a boss if we could get people to add a few more comments so it would be easier to tell what code did. His reply was that when consultant programmers who get to work on lots of code they didn’t write come into a new project, they run a script that removes all comments. He said comments are often misleading. I think that’s a little extreme, but if you turn comments into code, that documentation will always be there.
Source: A Python Aesthetic: Beauty and Why I Python by Brandon Rhodes