# Do your constants make sense?

Do you use constants in your code? Probably a lot. Even if you don’t define your own is highly probable that you use some constants defined by other libraries or a language itself. Constants are very powerful unless you use it in the wrong way.

## Why constants?

Let’s consider some math constants

const PI = 3.14159265;
const E = 2.71828183;

The value of Pi (or e) will never change in the future so it is a great candidate to put it into the constant. How does it look in our programs?

Everyone tells the difference between variable and const. It’s easy to imagine and the names of this two things leave no doubt. The value of constant doesn’t be changed during normal program execution but could be set by the developer, therefore quite often they are used to store configuration data, named states and many other things.

const API_KEY = "4c4712a4141d261ec0ca8f9037950685";
const VERSION = "9.4.1"
class Order
{
const STATE_NEW = 0;
const STATE_COMPLETE = 1;

private $state = self::STATE_NEW; public function finish() {$this->state = self::STATE_COMPLETE;
}
}

Constants describe the value, so the code is more readable and clean. If you use constants in this way, then it’s perfect. What if someone wants to get rid of all magic numbers and magic strings from code? Probably something like this:

class Printer extends AbstractPrinter
{
const FORMAT_A4 = "A4";

public function print($document,$format)
{
if ($format !== self::FORMAT_A4) { throw new Exception("Document should be in " . self::FORMAT_A4); }$this->handlePrint(\$document);
}
}

## Changing value of wrong-named constant

Now imagine that someone has to change the format in the printer, e.g. to B5. For this example, let’s assume, that it have to be done without creating a new implementation. The easiest way to do this is by changing the value of the constant FORMAT_A4:

const FORMAT_A4 = "B5";

It seems at least strange and may lead to misunderstanding and mistakes. The better name for this value is, for instance, PRINTER_FORMAT or simply FORMAT.

The previous example was a little bit exaggerated but it shows the main problem with naming things. We use constants to prevent doing changes in many places so, in conclusion, the name of the constant should be resistant to change their value. Name the constant according to the purpose of its value, rather than the value itself.

## Resources

This site uses Akismet to reduce spam. Learn how your comment data is processed.