Magic numbers used in level management demonstration

In loading scenes, there comes a topic that is very near and dear to my heart. That is the use of “magic numbers”.

For example:

SceneManager.LoadScene(1);

In this case, the “1” is the magic number. When looking at it in code, you will ask what is it? In professional development shops, there will typically be coding standards you must abide by, and a common one is that magic numbers can’t be used. They will fail code-reviews.

While it is absolutely fine to use “1” as it works, it is not very “readable”. To just point out to newer developers who are wanting to break into using C# professionally… or really any computer programming language really, be aware that you should go one step further and either define your levels with an enum value so that they are more readable, or use some kind of constant value to represent your level.

Example: instead of the code snippet above, create a new private constant variable at the top of your class:

private const int SECOND_LEVEL = 1;

Then you use that in your code to represent the second level instead of the number 1, which could represent anything at all.

SceneManager.LoadScene(SECOND_LEVEL);

This line of code is much more readable and thus maintainable. Sometimes these little things may seem silly to take the extra time to do, but undocumented code, magic numbers, and other things of this nature add up over time, to the tune of developers spending dozens of hours a week trying to decipher what things are in the code.

That translates into lost money. A developer is not cheap. Say you pay a developer $50 an hour to work on your project, and they spend 12-15 hours a week trying to go through murky code just trying to figure out what things are. Thats $600-$750 a week. For one developer.

What if your team has multiple developers (very common). I see this all the time in the companies I’ve worked for and the projects I have been a part of.

I just wanted to point that part out :wink: the course is great and I love it. Don’t take my critique the wrong way. (you may even address this later guys, I just haven’t gotten to it yet)

EDIT: indeed you discuss magic numbers a few lectures later. Lesson learned to me! :slight_smile: Thanks guys.

1 Like

Privacy & Terms