Create a variable to eliminate duplicity

One of the key aspects of programming is to eliminate duplicity. For example if you have some lines of code which are copied throughout a program it makes it very difficult to update the code. The major problem is that the code will need to be updated in many different areas. You may find a couple of instances of the code and you may miss some. This inevitably introduces bugs.

It doesn't matter how much code there is, we can eliminate duplicity from very small algorithms and statements. For example:

if (!is_dir($_SERVER['DOCUMENT_ROOT'] . '/cache/')) { mkdir($_SERVER['DOCUMENT_ROOT'] . '/cache/'); }

The above code first checks if a 'cache' directory exists and secondly if the directory does not exist, it creates it. This is a simple piece of code and if we left it as is it would be ok. But what we really want to do is eliminate the duplicate statements and create a variable:

$dir = $_SERVER['DOCUMENT_ROOT'] . '/cache/'; if (!is_dir($dir)) { mkdir($dir); }

The above code is better as we have removed the two directory locations and created a variable instead. This enables us to edit the code at a later stage more easily. There is also another area in which we can fix the code. We can make it more readable by changing the name 'dir' to something more meaningful.

$cacheDirectory = $_SERVER['DOCUMENT_ROOT'] . '/cache/'; if (!is_dir($cacheDirectory)) { mkdir($cacheDirectory); }

We have now eliminated our duplicate location statement with a variable and then have renamed the variable to a more meaningful name.