Magic numbers

Let’s refresh one of the previous lessons:

<?php

$eurosCount = 1000;
$dollarsCount = $eurosCount * 1.25; // 1250
$rublesCount = $dollarsCount * 60;  // 75000

print_r($rublesCount);

As far as professional development is concerned, such code “smells”. This expression describes a code that deviates from the so-called best practices. And here is why: at this point already looking at numbers 60 and 1.25, you’ll probably wonder: what are those numbers? Imagine looking at them in a month. How is another developer that has never seen that code before supposed to understand them? In the example above we can recover the context by correctly naming variables. In real life, however, code is much more complex, and often it’s impossible to guess what some numbers could possibly mean.

Such “smell” is called magic numbers. Numbers, origins of which are impossible to guess without a thorough knowledge of what’s happening in a particular part of the code.

It’s easy to fix it though: once you created properly named variables, all pieces fall into place.

<?php

$dollarsInEuro = 1.25;
$rublesInDollar = 60;

$eurosCount = 1000;
$dollarsCount = $eurosCount * $dollarsInEuro;   // 1250
$rublesCount = $dollarsCount * $rublesInDollar; // 75000

print_r($rublesCount);

Please note the following:

  • Variable names are in lowerCamelCase
  • The two new variables are separated from the calculations that follow them by an empty line. Those variables make sense even without calculations, so separating them we’ll increase the code readability.
  • As a result we got a properly named and structured code, but it’s longer then the previous version. It happens, and there’s nothing wrong with it. Code must be easy to follow.

instructions

Look at the code that outputs the overall number of rooms owned by the current king:

$king = 'King Balon the 6th';
print_r($king . ' has ' . (6 * 17) . ' rooms.');

As you see, these are magic numbers - it’s not clear what 6 and 17 refer to. If you knew the history of the royal family, however, you would know that every new king inherits all castles from ancestors and builds a new one - the exact copy of his parents’ castle.

This weird dynasty just produces identical castles…

Get rid of magic numbers, creating new variables, and print the following text to the screen.

Like this:

King Balon the 6th has 102 rooms.

A variable name must convey the meaning of the number and stay short enough, but at the same time it must be comprehensible so it’s easy to read.

Remember: code will work with any naming, and our system only checks the output result, so we rely on you to do this exercise properly.


Exercise available only for signed users.

Please sign in with your GitHub account, this is necessary to track the progress of the lessons. If you do not have an account yet, now is the time to create an account on Github.