Cleaner Coding — Methodizing Repetition

Methodizing repetitive commands makes your code more legible and less error prone.

A wonderful piece of advice from GameDevHQ so far has been: if feeling any difficulty, to brute force your implementation on the first iteration of code. First things first, make your code work. You don’t have to be perfect right away. Expensive and sloppy code is better than nonoperative code. Once your code works the way you want, you have the opportunity to come back later and clean things up.

A good lesson in cleaner code is: if you’re duplicating lines of code, there’s likely an opportunity to save space and time by combining them into a Method. In my game, there are two instances in which I want the Enemy to die. When my Enemy dies, some of the things I want to happen are:

  • Enemy can no longer damage the player
  • Enemy plays a sound and animation to communicate its demise
  • Enemy object and all of its components disappear from the game

Right now, this only amounts to seven lines of code, but as my game grows, so may the list of features accompanying the Enemy’s death.

In the image above, you’ll see two different sets of code. Both of them work the same way fundamentally. The difference is, in the optimized set on the right, I’ve combined the logic into one common method. When the Enemy dies, I create a method with which to handle all of the same behavior, and then any time I want the Enemy to die, I call upon that method.

This has two major benefits: it makes the code easier to understand for myself and others, and it makes my code less prone to error. Let’s say I want to adjust Enemy speed upon death. On the left, I have to change two lines of code and make sure they’re identical. On the right, only one line of code.

I define the method once, and when I want to add to it or change it I only have to look in one place. Any time I want that method to operate, I call upon it, and I know all the logic is in one place.