How Not To Pick Variables

Here is a small example showing how choosing good variable names can make a huge difference. Look at the following code block, and see how long it takes you to work out what it does. If you find it takes you a while, look at the improved code below that and see how much easier it is! Even with short variables that are words, not being descriptive makes debugging very difficult. Using letters on their own is frequently worse. Both code blocks are functionally identical, only variable names are changed.

import random
def brooms(hit):
    dig = hit+1
    while dig > hit or dig < 1:
        dig = int((str((random.random()*10)+0.5))[0])
    return dig
def monkey(cat,run):
    dodges = 0
    play = 1
    while dodges < run:
        red = brooms(cat)
        dodges += red
        print 'Loop:',str(play),'Roll:',str(red),'Sum: ',str(dodges)
        play += 1
Now for the fixed up code:
import random
def dice_roll(sides):
    roll = sides+1
    while roll > sides or roll < 1:
        roll = int((str((random.random()*10)+0.5))[0])
    return roll
def rolls_until(sides,sum_until):
    running_total = 0
    loop_count = 1
    while running_total < sum_until:
        current_roll = dice_roll(sides)
        running_total += current_roll
        print 'Loop:',str(loop_count),'Roll:',str(current_roll),'Sum: ',str(running_total)
        loop_count += 1

Did you find this post useful? You can leave me a buck or two with the Paypal donate button, support me on Patreon, or consider buying one of the "Suggested Resources" books on the side using my affiliate code (you pay the same price for the book, but I get a small referral fee from Amazon)!

Share This Post