The way of refactor

Victor Casañas
May 28 · 3 min read

A Laravel story about how to write clean code

So my story begins by trying to fix a bug, while doing this i noticed the code needed to be reshape a bit, so i will describe my journey.

So the code i need it to fix is the following

So first thing first, understanding what the code does, so usually before each refactor i always writing what the code does

Of course i develop using TDD but also DDD ( domain driven design), so this code is about to compute a “validity_date” attribute for a voucher but this bothers me a bit on a domain or natural language no one uses this term so the first refactor will be to find a natural term more appropriate so i chose “valid_unitl” attribute

Other thing that bothers me are comments, one example is this one

if ($this->orderDetail === null) {
// if voucher has never been purchased
$validityDate = $this->expiration_date;

Why this exist? why we cant use the comment as part of the code? so a better approach will be

if (! $this->was_purchased) {
$validityDate = $this->expiration_date;

so in order to make this, we just create a computed attribute

public function getWasPurchasedAttribute()
return $this->orderDetail !== null;

Other thing i noticed was the “$this->orderDetail->created_at;” it would be more simple to read like “$this->purchased_at;” so for this we can create another computed property

public function getPurchasedAtAttribute()
return $this->orderDetail->created_at;

Another thing that bothers me, of course other than bad weather, are the else statements so i usually remove them by just return early and after that we can have our first refactor looking like this

but still not happy, i don’t, like the second condition it seems that to much important thing happens on the if indentation part and it should be the opposite way, so another refactor will be to inverse the condition and let the important code be on the main indentation:

We can also see that we have the same return statement that we can put on the same if statement and finally we end with this pretty code:

I am a proud member of the disruptive Moonshiner Team. A Vienna based Software Development Company. We build your digital world.


Victor Casañas

Written by

A worldwide artisan developer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade