Code smells in PHP - Don't repeat yourself
Code smells allow us to spot traits in our code that may not stop it doing its job, but may indicate deeper rooted problems with the design of the code. I like the concept of code smells because it gives me a simple list of tells I can easily spot in my code which help improve the maintanability of that code. In this series we’ll go through some common code smells, why they’re bad, how to spot them and how to remove them from the codebase.
When you’re first learning to spot code smells, it is normally easier to write your code and then revisit it, refactoring it to remove the code smells as you go. Much of the time, trying to write perfect code from the off will result in code that is more complex than it needs to be and perfecting the design of the code through an iterative process generally produces better results.
Repeated code
I’ll start the series with repeated code. Repeated code is one of the easiest to spot, yet most misunderstood code smells. First of all, lets look at how The Pragmatic Programmer describes DRY:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.
We’re clearly not being told that you shouldn’t repeat any code whatsoever, what they’re saying is that the knowledge of the system (or the business rules) shouldn’t be repeated. This makes a lot more sense than just trying not to repeat any code at all.
The reason we shouldn’t repeat this code isn’t because we have to write more code. It’s because if we implement the same rules in multiple places across a codebase, there is a high chance that these rules will become out of sync with each other leading to strange issues in our code that can be hard to debug and not so great user experiences.
If you think you’re repeating yourself, imagine you had to change these rules, would you have to update more than once place in your code? If so, then maybe you need to look at refactoring your code to consolidate these rules into a single point of truth.
All that being said, your code should be precise and self documenting, if you can remove some repetitiveness to make it easier to read then that can’t be a bad thing. But if you’re obscuring the intent of your code in order to try not to repeat something then maybe you need to reconsider.