Skip to main content
Engineering LibreTexts

6.21: Don’t Reuse Variable Names

  • Page ID
    14573
  • Take a look at a few lines of code from the drawWorm() function again:

        wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
        pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)
        wormInnerSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)
        pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)
    

    Notice that two different Rect objects are created on lines 1 [199] and 3 [201]. The Rect object created on line 1 [199] is stored in the wormSegmentRect local variable and is passed to the pygame.draw.rect() function on line 200. The Rect object created on line 3 [201] is stored in the wormInnerSegmentRect local variable and is passed to the pygame.draw.rect() function on line 4 [202].

    Every time you create a variable, it takes up a small amount of the computer’s memory. You might think it would be clever to reuse the wormSegmentRect variable for both Rect objects, like this:

        wormSegmentRect = pygame.Rect(x, y, CELLSIZE, CELLSIZE)
        pygame.draw.rect(DISPLAYSURF, DARKGREEN, wormSegmentRect)
        wormSegmentRect = pygame.Rect(x + 4, y + 4, CELLSIZE - 8, CELLSIZE - 8)
        pygame.draw.rect(DISPLAYSURF, GREEN, wormInnerSegmentRect)
    

    Because the Rect object returned by pygame.Rect() on line 1 [199] won’t be needed after 2 [200], we can overwrite this value and reuse the variable to store the Rect object returned by pygame.Rect() on line 3 [201]. Since we are now using fewer variables we are saving memory, right?

    While this is technically true, you really are only saving a few bytes. Modern computers have memory of several billion bytes. So the savings aren’t that great. Meanwhile, reusing variables reduces the code readability. If a programmer was reading through this code after it was written, they would see that wormSegmentRect is passed to the pygame.draw.rect() calls on line 2 [200] and 4 [202]. If they tried to find the first time the wormSegmentRect variable was assigned a value, they would see the pygame.Rect() call on line 1 [199]. They might not realize that the Rect object returned by line 1's [199] pygame.Rect() call isn’t the same as the one that is passed to the pygame.draw.rect() call on line 4 [202].

    Little things like this make it harder to understand how exactly your program works. It won’t just be other programmers looking at your code who will be confused. When you look at your own code a couple weeks after writing it, you may have a hard time remembering how exactly it works. Code readability is much more important than saving a few bytes of memory here and there.

    For additional programming practice, you can download buggy versions of Wormy from http://invpy.com/buggy/wormy and try to figure out how to fix the bugs.