Magic Numbers
Your code should not include magic numbers.
- A magic number is a number used outside of a variable assignment in code that does not have an immediate and clear meaning.
- In general, every number besides -1, 0, 0.5, 1, 2, and 10 is magic.
- If you must use a magic number, store the number or an expression using the number in a variable, then use that variable.
2-point error: using any magic numbers.
Example: Here's code to draw a grid of clocks, similar to what you saw in the graphics notes. For numbers like 80 (the width and height of the clocks) note that we're storing them in variables so that we can change the behavior of our code easily.
# Draw a whole grid of clocks! (Without magic numbers!)
def drawClockGrid(canvas, width, height):
clockWidth = 80
clockHeight = 80
numRows=3
numCols=4
margin = 5
hour = 0
minute = 0
incrementHour = 13
for row in range(numRows):
for col in range(numCols):
left = col * clockWidth + margin
top = row * clockHeight + margin
right = left + clockWidth - margin
bottom = top + clockHeight - margin
hour += incrementHour
drawClock(canvas, left, top, right, bottom, hour, minute)
Now, this is the same code, but written using magic numbers. This code is hard to understand, changing this code's behavior is difficult, and it's very easy to break. Don't do this!
# Magic numbers! Don't do this!
def drawClockGrid(canvas, width, height):
hour = 0
for row in range(3):
for col in range(4):
left = col * 80 + 5
top = row * 80 + 5
right = col * 80 + 80
bottom = row * 80 + 80
hour += 13
drawClock(canvas, left, top, right, bottom, hour, 0)
This is even worse!
# DEFINITELY don't do this!
def drawClockGrid(canvas, width, height):
hour = 0
for row in range(3):
for col in range(4):
hour += 13
drawClock(canvas, col*80+5, row*80+5, col*80+80, row*80+80, hour, 0)