Don’t Repeat Yourself (DRY)

Code duplication is bad and should be avoided. You should do your best to make sure you don’t repeat yourself (DRY). This is one of the most important principles in programming.

Repeating code is a waste. Every line of code you create requires maintenance and increase the chance of bugs. It bloats your code base if you have duplicate code all over the place. Small changes requires a lot of work because you need to make changes on multiple places and also test each change you make. So a good practice is to avoid duplicate code.

The first step to remove duplicate code is to follow the clean code principles. The most important one is Single Responsibility Principle (SRP). It’s easy to implement but still a lot of programmers don’t apply it.
If you create many small classes and functions then you naturally decrease duplicate code. The smallest piece of code you can put in a function and use on multiple places.

Another way to avoid duplicate code is to make sure you have abstracted enough. Sometimes you still have duplicate code after creating a lot of small classes and functions. And this might be because you have 2 or more slightly different things which share a lot in common. The differences they have force you to place them in separate functions. You need to get the abstraction right to make sure no duplicate code exists. So whenever you still see duplicate code, then you need to abstract more.

Bad

Here we repeated our self because we did not add abstraction.

<?php
function renderButtons(array $buttons): void
{
    foreach ($buttons as $button) {
        $button->translateText();
        $html = $button->generateHtml();
        $this->addToForm([
            $html,
        ]);
    }

}

function renderInputs(array $inputs): void
{
    foreach ($inputs as $input) {
        $input->translateText();
        $html = $input->generateHtml();
        $this->addToForm([
            $html,
        ]);
    }
}

Good

Now if we abstract buttons and Inputs as elements. Then we don’t need to repeat ourself and we can do this.

<?php
function renderUIElements(array $elements): void
{
    foreach ($elements as $element) {
        $element->translateText();
        $html = $element->generateHtml();
        $this->addToForm([
            $html,
        ]);
    }
}

Conclusion

The conclusion is DRY. Meaning Don’t Repeat Yourself. You can do this by creating many small class and functions and then make sure you have correctly abstracted your code. If you create duplicate code, that means you haven’t spend enough time designing your classes and functions and you need to take a step back and think to abstract more!