Tips for writing maintainable code

If you have ever worked in a team or in any other way had to maintain others people code, you already know how important is to write maintainable code. Actually, this doesn’t need to be others people code at all – if you are trying to modify your year-old-code, you may already forgot all the details around it and it may be hard for you to read it, let alone modify it.
Since there are many articles on this topic, I will just mention for you few easy starting tips, something that we always have to teach our interns and junior developers.
Stick to coding standards
Whenever you do some work, try to stick to some coding standard to make your coding style consistent. If you are working with framework, that framework most likely has some coding standard. If not, discuss it with your team as it will make your life easier.
If you are reading this, most likely you are working with Magento. In that case, you should read what official documentation has to say about it. Also, set up your IDE to do those validations automatically for you.
Write meaningful comments
I know, everyone has heard about code comments and uses them. But how many times have those comments been useful to you? From my experience, they most often resemble something like this:
// we multiply it by 3
$result = $firstNumber * 3;
Of course we did multiply it by 3. However, nothing here about this code is obvious. For what reason? Why now? Why 3? Luckily there is one rule you need to remember about this:
“Code tells you how, comments tell you why”
Stick to that, and your comments will have much more sense.
Use conditions wisely
For starters, stop using else where it is not required, like in the example below:
function something($condition) {
if ($condition < 10) {
return false;
} else {
// do something else;
}
}
If you put the code this way, becomes much readable:
function something($condition) {
if ($condition < 10) {
return false;
}
// do something else;
}
Another thing that I often see is whole functions being wrapped in if statements like this:
function something($count) {
if ($count > 0) {
applyDiscounts();
getShippingRates();
sumbitTrackingInfo();
}
}
That example may be short, but in complex code it becomes a problem. Especially if you have another condition nested inside it. Instead, try to reverse your condition and escape the function early like this:
function something($count) {
if ($count <= 0) {
return;
}
applyDiscounts();
getShippingRates();
sumbitTrackingInfo();
}
It is easier to have visual separation of checks and logic, rather than tracking the nesting levels and what falls inside and outside of code blocks.
Avoid function with too many parameters
Although sometimes simply required, in most cases this just means that you have a single entry point that is supposed to handle a lot of edge cases. This is bad, because if your tests do not cover every possibility (and they most likely don’t), modifying something here will probably cause issues in other parts of the system. For an example:
function renderMenu($title, $body, $option1 = true, $options2 = false, $options3 = true);
We have 3 optional parameters, which will not make anyone happy who needs to modify this. Of course, it is not an option to break DRY yourself, but perhaps you made a mistake earlier. Maybe all you need is a $menuConfig parameter that will be responsible for all validation and config handling. Maybe you do not need those options at all here, but you need to implement decorator pattern. Next time you find yourself writing a function that has more than 2-3 parameters, stop and think if you are doing something wrong.
Use tools that can help you detect complexity and overall mess
In the end, you can always use tools such as phpcs and phpmd that will help you avoid most common pitfalls. It is rather easy to set those up (also, it is topic for another article), but you should definitely try it.
One of my favorite checks in this areas is the one for cyclomatic complexity, which is a good indicator for when you need a code refactoring as obviously something is not right. Using the code sniffer, you can even trigger it for single file or folder like this:
phpcs -p --sniffs=Generic.Metrics.CyclomaticComplexity --standard=Generic <file/folder>
Which outputs something like this:
FILE: ../app/code/core/Mage/Sales/Model/Quote.php
------------------------------------------------------------------------------------------------------
FOUND 0 ERRORS AND 2 WARNINGS AFFECTING 2 LINES
------------------------------------------------------------------------------------------------------
956 | WARNING | Function's cyclomatic complexity (13) exceeds 10; consider refactoring the function
1644 | WARNING | Function's cyclomatic complexity (11) exceeds 10; consider refactoring the function
------------------------------------------------------------------------------------------------------
Default parameters for error/warning threshold are just ok. So if you got something like this, listen to phpcs and consider refactoring the function.
And finally…
We can go on this subject for quite a while. So remember, these are just some beginners tips. If you are unsure, you can always request a code review (if that is not part of your development process, which it really should be) from one or more senior members of the team. As there has been, and still is, only one true measurement of code quality:
2 comments
I would also mention PHPstorm’s functionalities for reformatting code and code inspection.. been very helpful to me. Also, PHPstorm can give early heads up for PHP version compatibility and such.
Great Post,
Thanks for sharing writing maintainable code. Magento developer should know this techniques and implement it