Programming Tidbit #1 - Eliminate Magic Numbers
This is the first post in the series “Programming Tidbits.” These articles consist of useful bits of information or code that I would like to share, but may not be considered a full article.
The Wrong Thing…
When programming, a lot of times you may find yourself throwing together some code which uses “Magic Numbers.” A magic number is basically just any static number sitting in your code such as:
public function moveMyCharacter() : void
{
myCharacter.x += 5;
myCharacter.y += 5;
}
public function damageEnemy() : void
{
someEnemy.health -= 20;
}
Why is it bad?
Now obviously that is just a simple example, but let’s say you have code ALL OVER your project using these “magic numbers.” What happens then, if later you want to change these numbers? You have a long and tedious process of finding all times that they are used. Not only that, but you are prone to missing something which will therefore lead to unpredictable code and bugs.
The right thing…
Instead of being mean to yourself, do the right thing and create constants or variables for all of your magic numbers. The usual place to put them is at the top of your class. Even better would be to externalize the data into some sort of settings file ( if the data is worthy of course ). I’ll be discussing externalizing data in a future article if you aren’t quite sure how to go about that…
So here is the code once again, done properly.
// Top of your Class somewhere...
private const MOVE_SPEED:int = 5;
private const HERO_DAMAGE:int = 20;
public function moveMyCharacter() : void
{
myCharacter.x += MOVE_SPEED;
myCharacter.y += MOVE_SPEED;
}
public function damageEnemy() : void
{
someEnemy.health -= HERO_DAMAGE;
}


(3 votes, average: 4.67 out of 5)



