I've been programming in PHP now for almost ten years, and if there is one thing I learned over this period, it's that readability and simplicity are the keys for maintainable and sustainable code. Every first attempt to write code should be about making it work. Only after that, you should take some time to refactor. This is when I aim for readability and simplicity. Today I see refactoring as one of my main skills. In this post, I share with you my refactoring practices for PHP.
Refactoring is the process of modifying and restructuring code without changing its functionality. When I first heard
about it, I was like:
Why would anyone do that? It took some years until I fully understood the concept and that the working code is not always good. So with refactoring, you can make working code better, and what better means is something developers will argue for hours. In the end, you have to define it for yourself.
Stage 1#1 - Be Expressive
This might be an easy tip, but writing expressive code can improve it a lot. Always make your code self-explaining so that you, your future self or any other developers who stumble over your code knows what is going on.
But then developers also say naming
is one of the hardest things in programming. This is one reason why this is not as easy as it sounds. ๐คทโ
Note: Make sure to hit the "Show/Hide Notes" buttons on the code examples to get
details about why we needed to change the code.
Example #1 - Naming
PHP
1$status = $user->status('pending');
1// โ It is unclear what this method is doing with the provided string
2// โ Are we setting the status? Are we checking the status?
3$status = $user->status('pending');
1$isUserPending = $user->isStatus('pending');
1// โ By adding "is" to the names we make our intentions more clear
2// โ We are checking if the status of the user equals the given string
3// โ Also the new variable name lets us assume it will be a boolean
This is an example of one of my projects from last year. We had a command-line command to import users. The class ImportUsersCommand contains a handle method to perform the tasks.
PHP
1protectedfunctionhandle()
2{
3 $url = $this->option('url')?: $this->ask('Please provide the URL for the import:');
The concept of early returns refers to a practice where we try to avoid nesting by breaking a structure down to specific cases. In return, we will get a more linear code, which is much easier to read and grasp. Every case is separated and good to follow. Don't be afraid of using
multiple return statements.
Example #1
PHP
1publicfunctioncalculateScore(User $user):int
2{
3if($user->inactive){
4 $score =0;
5}else{
6if($user->hasBonus){
7 $score = $user->score + $this->bonus;
8}else{
9 $score = $user->score;
10}
11}
12
13return $score;
14}
1publicfunctioncalculateScore(User $user):int
2{
3if($user->inactive){
4 $score =0;
5}else{
6// โ What was "if" again?
7if($user->hasBonus){
8 $score = $user->score + $this->bonus;
9}else{
10// โ Your ๐ are constantly moving due to the different idention levels
11 $score = $user->score;
12}
13}
14
15return $score;
16}
1publicfunctioncalculateScore(User $user):int
2{
3if($user->inactive){
4return0;
5}
6
7if($user->hasBonus){
8return $user->score + $this->bonus;
9}
10
11return $user->score;
12}
1publicfunctioncalculateScore(User $user):int
2{
3// โ Edge-cases are checked first
4if($user->inactive){
5return0;
6}
7
8// โ Every case has its own section which makes them easy to follow step by step
Note: You sometimes also hear the term "guard-clauses" which is what you can achieve with early returns. You are guarding your method from special conditions.
Stage 3#3 - Refactor To Collections
In PHP, we work a lot with arrays of different data. The available features to handle and transform those arrays are quite limited in PHP and don't provide a good experience. (array_walk, usort, etc.)
To tackle this problem, there is this concept of Collection classes, which help you handle arrays. Most known is the implementation in Laravel, where a collection class provides you with dozens of useful features to work with arrays.
Note: For the following examples, I will use Laravel's collect() helper, but the approach is very similar with other available collection classes from other frameworks or libraries.
Example #1
PHP
1$score =0;
2
3foreach($this->playedGames as $game){
4 $score += $game->score;
5}
6
7return $score;
1// โ Here we have a temporary variable
2$score =0;
3
4// โ It is ok to use a loop, but it could be more readable
Note: Adam Wathan wrote a book
about how to use collections to never write a loop again which I can highly recommend.
Stage 4#4 - Consistency
Every line of code adds a little amount of visual noise. The more code, the more difficult it gets to read. This is why it is essential to set rules. Keeping similar things consistent will help you recognize code and patterns. It will result in less noise and more readable code.
Example #1
PHP
1classUserController
2{
3publicfunctionfind($userId)
4{
5
6}
7}
8
9classInvoicesController
10{
11publicfunctionfind($user_id){
12
13}
14}
1classUserController
2{
3// โ Decide how to name variables (camelCase, snake_case, etc.) Don't mix!
4publicfunctionfind($userId)
5{
6
7}
8}
9
10// โ Choose between singular or plural for all controllers and stick to it
11classInvoicesController
12{
13// โ Changes in style, like position of braces, make your code hard to read
14publicfunctionfind($user_id){
15
16}
17}
1classUserController
2{
3publicfunctionfind($userId)
4{
5
6}
7}
8
9classInvoiceController
10{
11publicfunctionfind($userId)
12{
13
14}
15}
1classUserController
2{
3// โ camelCase Naming for all variables
4publicfunctionfind($userId)
5{
6
7}
8}
9
10// โ Controller names consistent (singular in this case)
11classInvoiceController
12{
13// โ Consistent position of braces (format) makes code more readable
I already mentioned that refactoring doesn't change the functionality of your code. This comes handy when running tests, because they should work after refactoring too. This is why I only start to refactor my code, when there are tests. They will assure that I don't unintentionally change the behaviour of my code. So don't forget to write tests or even go TDD.
Conclusion
This is how I refactor PHP. In the end, you and your team have to decide how you want your code to be. Just make sure to define it, write it down, and save enough time to make it happen after your code is working. I started with my main principles and I plan to cover more topics soon. If you have refactoring tips you'd like to share, just ping me on Twitter.