7 Tips to Prevent, Detect, and Fix Bugs In Your Code


November 8th, 2019


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:

  1. 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?


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.

  1. 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:

1public function addTickets($quantity)
3 foreach (range(1, $quantity) as $i)
4 {
5 $code = Code::generate(); }
6 $this->tickets()->create(
7 [
8 'code' => $code,
9 ]);
10 }
1public function addTickets($quantity)
3 foreach (range(1, $quantity) as $i) {
4 $code = Code::generate();
5 }
7 $this->tickets()->create([
8 'code' => $code,
9 ]);

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.

  1. 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:

1$contact = array();
2$contact['firstname'] = $user->first_name;
3$contact['surname'] = $user->last_name;
4$contact['id'] = $user->id;
5$contact_emails = array();
6$contact_email = array();
7$contact_email['email'] = $user->email;
8$contact_emails[] = $contact_email;
9$contact['emails'] = $contact_emails;
11$this->create('contact', $contact);
1$contact = [
2 'id' => $user->id,
3 'firstname' => $user->first_name,
4 'surname' => $user->last_name,
5 'emails' => [
6 [
7 'email' => $user->email,
8 ],
9 ],
12$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:

1public function addTickets($quantity)
3 foreach (range(1, $quantity) as $i) {
4 $this->tickets()->create([
5 'code' => Code::generate(6),
6 ]);
7 }

However, in some scenarios, using local variables can improve the clarity of the code, for example:

1function calculateCode($price, $quantity, $deliveryCost)
3 $subtotal = $price * $quantity;
5 if ($subtotal < 30) {
6 $subtotal += $deliveryCost;
7 }
9 return $subtotal;

Might be clearer than:

3function calculateTotal($price, $quantity, $deliveryCost)
5 if ($price * $quantity < 30) {
6 return $price * $quantity + $deliveryCost;
7 }
9 return $price * $quantity;
  1. 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:

1if ($subtotal < DELIVERY_COST_THRESHOLD) {
2 $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.

  1. 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:

1$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:

1$subtotal = $item->price * $quantity;
2$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:

1return $this->addDeliveryCost($price * $quantity);

Declaring and using many small methods is a great way to reduce the need for temporary variables in our code.

  1. 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:

1// Somewhere in UserController.php
4 'name' => $request->name,
5 'email' => $request->email,
6 'password' => bcrypt($request->password),

You should write it this way instead:

1// Somewhere in UserController.php
4 new UserCreationCommand(
5 new UserNameField($request->name),
6 new UserEmailField($request->email),
7 new UserPasswordField(bcrypt($request->password)),
8 )

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:

1class UserCreationCommandHandler
3 //...
5 public function handle(UserCreationCommand $command)
6 {
7 $this->userRepository->create(
8 $command->name,
9 $command->email,
10 $command->password,
11 );
12 }

Eventually, inside UserEloquentRepository, you will end up calling User::create:

1class UserEloquentRepository implements UserRepository
3 //...
5 public function create(
6 UserNameField $name,
7 UserEmailField $email,
8 UserPasswordField $password
9 ) {
10 return User::create([
11 'name' => $name->getValue(),
12 'email' => $email->getValue(),
13 'password' => bcrypt($password->getValue()),
14 ]);

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:

  1. 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:

1function test_order_without_delivery_cost()
3 $order = new Order;
4 $order->addItem(new Item(['price' => 20]), 5);
6 $expectedTotal = 20 * 5;
7 $this->assertSame($expectedTotal, $order->getTotal());
10function test_order_with_delivery_cost()
12 $order = new Order;
13 $order->addItem(new Item(['price' => 20]), 1);
15 $expectedTotal = 20 + DELIVERY_COST;
16 $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.

Filed in:

Duilio Palacios

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.

Laravel News Partners