The way of refactor

The way of refactorVictor CasañasBlockedUnblockFollowFollowingMay 28A Laravel story about how to write clean codeSo 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 followingSo first thing first, understanding what the code does, so usually before each refactor i always writing what the code doesOf 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” attributeOther thing that bothers me are comments, one example is this oneif ($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 beif (! $this->was_purchased) { $validityDate = $this->expiration_date;}so in order to make this, we just create a computed attributepublic 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 propertypublic 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 thisbut 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.

FIN.

. More details

Leave a Reply