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

Published on by

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

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?

$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.

  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:

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.

  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:

$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;
}
  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:

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.

  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:

$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.

  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:

// 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:

  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:

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.

Duilio Palacios photo

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.

Filed in:
Cube

Laravel Newsletter

Join 40k+ other developers and never miss out on new tips, tutorials, and more.

image
Tinkerwell

Version 4 of Tinkerwell is available now. Get the most popular PHP scratchpad with all its new features and simplify your development workflow today.

Visit Tinkerwell
Laravel Forge logo

Laravel Forge

Easily create and manage your servers and deploy your Laravel applications in seconds.

Laravel Forge
Tinkerwell logo

Tinkerwell

The must-have code runner for Laravel developers. Tinker with AI, autocompletion and instant feedback on local and production environments.

Tinkerwell
No Compromises logo

No Compromises

Joel and Aaron, the two seasoned devs from the No Compromises podcast, are now available to hire for your Laravel project. ⬧ Flat rate of $7500/mo. ⬧ No lengthy sales process. ⬧ No contracts. ⬧ 100% money back guarantee.

No Compromises
Kirschbaum logo

Kirschbaum

Providing innovation and stability to ensure your web application succeeds.

Kirschbaum
Shift logo

Shift

Running an old Laravel version? Instant, automated Laravel upgrades and code modernization to keep your applications fresh.

Shift
Bacancy logo

Bacancy

Supercharge your project with a seasoned Laravel developer with 4-6 years of experience for just $2500/month. Get 160 hours of dedicated expertise & a risk-free 15-day trial. Schedule a call now!

Bacancy
LoadForge logo

LoadForge

Easy, affordable load testing and stress tests for websites, APIs and databases.

LoadForge
Paragraph logo

Paragraph

Manage your Laravel app as if it was a CMS – edit any text on any page or in any email without touching Blade or language files.

Paragraph
Lucky Media logo

Lucky Media

Bespoke software solutions built for your business. We ♥ Laravel

Lucky Media
Lunar: Laravel E-Commerce logo

Lunar: Laravel E-Commerce

E-Commerce for Laravel. An open-source package that brings the power of modern headless e-commerce functionality to Laravel.

Lunar: Laravel E-Commerce
DocuWriter.ai logo

DocuWriter.ai

Save hours of manually writing Code Documentation, Comments & DocBlocks, Test suites and Refactoring.

DocuWriter.ai
LaraJobs logo

LaraJobs

The official Laravel job board

LaraJobs
All Green logo

All Green

All Green is a SaaS test runner that can execute your whole Laravel test suite in mere seconds so that you don't get blocked – you get feedback almost instantly and you can deploy to production very quickly.

All Green
Larafast: Laravel SaaS Starter Kit logo

Larafast: Laravel SaaS Starter Kit

Larafast is a Laravel SaaS Starter Kit with ready-to-go features for Payments, Auth, Admin, Blog, SEO, and beautiful themes. Available with VILT and TALL stacks.

Larafast: Laravel SaaS Starter Kit
SaaSykit: Laravel SaaS Starter Kit logo

SaaSykit: Laravel SaaS Starter Kit

SaaSykit is a Laravel SaaS Starter Kit that comes with all features required to run a modern SaaS. Payments, Beautiful Checkout, Admin Panel, User dashboard, Auth, Ready Components, Stats, Blog, Docs and more.

SaaSykit: Laravel SaaS Starter Kit
Rector logo

Rector

Your partner for seamless Laravel upgrades, cutting costs, and accelerating innovation for successful companies

Rector

The latest

View all →
Automatic Blade Formatting on Save in PhpStorm image

Automatic Blade Formatting on Save in PhpStorm

Read article
PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More image

PhpStorm 2024.1 Is Released With a Integrated Terminal, Local AI Code Completion, and More

Read article
Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released image

Laravel Prompts Adds a Multi-line Textarea Input, Laravel 11.3 Released

Read article
Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite image

Bartender Is an Opinionated Way to Authenticate Users Using Laravel Socialite

Read article
Jeffrey Way's PhpStorm Setup in 2024 image

Jeffrey Way's PhpStorm Setup in 2024

Read article
Easily Optimize PDFs in Laravel with the Optimizer Package image

Easily Optimize PDFs in Laravel with the Optimizer Package

Read article