Remove Comments By Making Them Code

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:

[cc lang=”python”]
# is window too tall
if window.height > 100:
fix_window_height()
[/cc]

Becomes:

[cc lang=”python”]
IsWindowTooTall = window.height > 100
if IsWindowTooTall:
fix_window_height()
[/cc]

Example:
[cc lang=”python”]
widget.reset(True) # forces re-draw
[/cc]

becomes:

[cc lang=”python”]
force_redraw = True
widget.reset(force_redraw)
[/cc]

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:
[cc lang=”python”]
# open the barn
barn = code.Barn.get()
barn.unlock()
barn.open()

# saddle the horse
saddle = code.Saddle.get()
saddle.install(horse)
[/cc]

Becomes:

[cc lang=”python”]
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)
[/cc]

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

Submit a Comment

Your email address will not be published. Required fields are marked *