Hello all,
So, a couple of weeks ago on MGM, I went into a basic overview of what OOP is. If you don’t know what that is or want to refresh your memory on that, the blog post is here.
Anyways, so today, I’m going to talk about one of the major goals of using OOP: the DRY principle.
What does DRY stand for?
It stands for “Don’t Repeat Yourself”. Basically, DRY means that you do not want to repeat code of which you’ve already written on a different page or even repeat code on the same page.

Why is DRY important? Well, to answer this question, let’s look at an example.
Suppose you have the following code on one page:
$number = 10;
$multiplier = 2;
$answer = $number * $multiplier;
echo $answer;
And this code on another page:
$number = 7;
$multiplier = 4;
$answer = $number * $multiplier;
echo $answer;
So, with this code in mind, let’s propose that now you want to do subtraction instead of multiplication. So now, you have to update both of those pages to subtract instead of multiply. I know, a very simple example here, but just imagine if you have 100+ pages each with 700+ lines of code, and you have to find and fix all of these. Pretty daunting now, isn’t it?
Well, with DRY, all we have to do is create one function in order to handle a change like this. So, let’s create a function!
function domath($number1, $number2)
{
$result = $number1 * $number2;
return $result;
}
Very simple function above. So, the pages using this function will look like this:
$number = 10;
$multiplier = 2;
$answer = domath($number, $multiplier);
echo $answer;
And the other page:
$number = 7;
$multiplier = 4;
$answer = domath($number, $multiplier);
echo $answer;
So, let’s suppose the scenario above: you decide to subtract instead of multiply. Well, all you have to do is adjust the code on the function! The function will now look like this:
function domath($number1, $number2)
{
$result = $number1 - $number2;
return $result;
}
And that’s it, you’re done! That’s the DRY principle in effect!
So, how exactly does this apply to OOP? Well, that’s one of the major points in using OOP: not repeating yourself. Classes are a great way in order to only have to change code in one place instead of having to change code in MANY different areas.
That is DRY for you: Don’t Repeat Yourself, and you will have much more bliss as a programmer.
That’s all for now, until next time…keep that tech gear ticking.
~Goliath7470
