Keeping track of constants

This is a simple little trick that I learned while I was at Game Circus. Basically, the goal is to never have any string constants or number literals littered throughout your code. Instead, you want to make one constant and place it at the top of the file. This is usually an obvious idiom to most programmers, but you may not realize how important it is.

The reason you want to do this is because if you used, for example, the value 0.004f in a few places within your cpp file, but you want to change that value, you’ll have to change all the places where you used it. It’s easy to forget one or two though, which is the problem.

So the idea is to group them all together at the top of the cpp file and make them static and const. It’s much easier to do this if you have primitive data types versus classes. It’s also better to have the value stored in the cpp file. If you store it in the header file, every time you need to change it, it has to recompile all the cpp files that include that header. So the compile time is actually faster if you keep them defined in the .cpp file like this.

The reason it’s good to make the value static is because it will only make one copy of it for that class. You obviously want it to be const because that will guarantee that it won’t change.

Header file.

Cpp file.

Of course, it’s up to you to change things around. For example, you may want to make them private instead of public. You can move them outside of the class too, or just within the namespace, but this will pollute the namespace, unless that’s your intent.

As a side note with regards to localization: Ideally, you would put all of your strings in something like a spreadsheet. One column for “English”, one column for “Spanish”, etc. Then you simply implement a “fetch” function that will automatically grab the correct string based on a language setting.

Leave a Reply

You must be logged in to post a comment.