7 Tips to Prevent, Detect, and Fix Bugs In Your Code
Published on by Duilio Palacios
With every line of code we add to our projects, we increase their complexity and the possibility of introducing bugs that can pop up at inopportune times. Perhaps a few minutes before a client’s meeting or during a weekend when we are at the cinema, away from our keyboard.
To prevent those scary situations, let’s go over seven tips for writing better code:
- Assign descriptive names to your variables, functions, parameters, and methods:
Code is written only once but read and interpreted many times — both by other developers and you. Therefore, it’s worthy of dedicating a few extra seconds to name that new class or method, so its name reveals its true intention or content.
Let’s compare these two lines. Which one is easier to understand?
$evnt->add($req->q);
$event->addTickets($request->quantity);
The first line has a typo, the add
method is not clear about what has been added, the variable $req
is not clear enough, and it’s difficult to understand that q
refers to quantity.
The second example, on the other hand, can be easy to understand even for non-developers.
- Use a standard like PSR-2 for PHP
Never underestimate the importance of writing code in an orderly and consistent way because that will allow you to spot problems more quickly.
Consider the following two examples:
public function addTickets($quantity){ foreach (range(1, $quantity) as $i) { $code = Code::generate(); } $this->tickets()->create( [ 'code' => $code, ]); }
public function addTickets($quantity){ foreach (range(1, $quantity) as $i) { $code = Code::generate(); } $this->tickets()->create([ 'code' => $code, ]);}
Both blocks of code have the same bug: both create only one ticket when they should create N. But in which block did you spot the problem more quickly? Now imagine the consequences of dealing with a complex code with the wrong format.
- Reduce the number of temporary variables
Although one of the first concepts we learn in algorithms is how to declare and use temporary variables, they can make the code harder to read and maintain:
Consider the following examples:
$contact = array();$contact['firstname'] = $user->first_name;$contact['surname'] = $user->last_name;$contact['id'] = $user->id;$contact_emails = array();$contact_email = array();$contact_email['email'] = $user->email;$contact_emails[] = $contact_email;$contact['emails'] = $contact_emails; $this->create('contact', $contact);
$contact = [ 'id' => $user->id, 'firstname' => $user->first_name, 'surname' => $user->last_name, 'emails' => [ [ 'email' => $user->email, ], ],]; $this->create('contact', $contact);
Which example is easier to understand?
And, by the way, it’s bad practice to align equal symbols. That not only goes against PSR-2; it can also make the code more difficult to maintain.
So, going back to our tickets example, the example can be improved if we eliminate the code
variable and inline the code instead:
public function addTickets($quantity){ foreach (range(1, $quantity) as $i) { $this->tickets()->create([ 'code' => Code::generate(6), ]); }}
However, in some scenarios, using local variables can improve the clarity of the code, for example:
function calculateCode($price, $quantity, $deliveryCost){ $subtotal = $price * $quantity; if ($subtotal < 30) { $subtotal += $deliveryCost; } return $subtotal;}
Might be clearer than:
<?php function calculateTotal($price, $quantity, $deliveryCost){ if ($price * $quantity < 30) { return $price * $quantity + $deliveryCost; } return $price * $quantity;}
- Don’t use “Magic numbers.”
If orders below 30 USD will have a delivery cost, we should reveal that knowledge with a property, constant or configuration variable like this:
if ($subtotal < DELIVERY_COST_THRESHOLD) { $subtotal += $deliveryCost;}
In that way, we reveal our intentions, and we can also reuse the constant in other parts of the project.
If we ever need to change the delivery threshold, we’ll only have to update one line in our code, by reducing duplication we also reduce the possibility of forgetting to update one of the places that previously used the magic number.
- Divide and conquer
Many examples and code scenarios can be improved by separating the code in small methods, each one with a different responsibility. For example:
The new method getContactInfo
will return an array with the users contact information:
$this->create('contact', $user->getContactInfo());
Object-oriented programming asks us to group data and functions in one place (classes). We’ll assemble the array with the contact information in the same place we have all the user info (the
User
model).
Let’s see another example:
$subtotal = $item->price * $quantity;$subtotal = $this->addDeliveryCost($subtotal);
The method addDeliveryCost
will return the amount with the delivery cost, but only if the amount does not exceed the delivery threshold, otherwise it will return the original amount.
Now let’s delete the local variable and inline the code:
return $this->addDeliveryCost($price * $quantity);
Declaring and using many small methods is a great way to reduce the need for temporary variables in our code.
- Default to simple solutions
Many tutorials that promise you will write better code end up explaining how to over-complicate code that could be simple otherwise.
Those tutorials tell you that if you are working with Laravel and Eloquent, it is wrong to put this code in your controller:
// Somewhere in UserController.php User::create([ 'name' => $request->name, 'email' => $request->email, 'password' => bcrypt($request->password),]);
You should write it this way instead:
// Somewhere in UserController.php $this->commandTransport->handleCommand( new UserCreationCommand( new UserNameField($request->name), new UserEmailField($request->email), new UserPasswordField(bcrypt($request->password)), ));
And then, inside the UserCreationCommandHandler
class, you won’t create the user either because that would go against SOLID principles. You should use a repository instead:
class UserCreationCommandHandler{ //... public function handle(UserCreationCommand $command) { $this->userRepository->create( $command->name, $command->email, $command->password, ); }}
Eventually, inside UserEloquentRepository
, you will end up calling User::create
:
class UserEloquentRepository implements UserRepository{ //... public function create( UserNameField $name, UserEmailField $email, UserPasswordField $password ) { return User::create([ 'name' => $name->getValue(), 'email' => $email->getValue(), 'password' => bcrypt($password->getValue()), ]);} }
After half an hour of work, the client calls you and asks you to add another field to the User model.
Which example is going to take longer to fix? In which case is it going to be more likely that you’ll introduce a bug? (like forgetting to pass one field from one method to the next one).
And, by the way, did you noticed I called bcrypt
twice in the example with commands and repositories? So that second example has a bug!
Unfortunately, a dozen interfaces and classes won’t prevent you from making an error. In any case, you have to test your code very carefully. And speaking of testing code:
- Write automated tests
Accountants follow a practice called “Double-entry bookkeeping”—a method that requires them to enter all transactions twice. Writing unit tests requires us to write the code twice, one to define each test:
function test_order_without_delivery_cost(){ $order = new Order; $order->addItem(new Item(['price' => 20]), 5); $expectedTotal = 20 * 5; $this->assertSame($expectedTotal, $order->getTotal());} function test_order_with_delivery_cost(){ $order = new Order; $order->addItem(new Item(['price' => 20]), 1); $expectedTotal = 20 + DELIVERY_COST; $this->assertSame($expectedTotal, $order->getTotal());}
And a second time to write the actual implementation of the code (which I’ll leave as an exercise for the reader).
Many developers complain about this practice because it forces us to “work double”, but by writing the code twice, we reduce the possibility of making the same mistake, twice and in the same way (if we make two different mistakes, tests are likely to fail). This is why projects that implement some unit testing tend to have fewer bugs and will require fewer hours of debugging.
I am a PHP/Laravel developer and teacher. I created Styde.net, a website dedicated to teach PHP, Laravel, Vue.js and other web technologies to the Spanish community.