Messy Code V/S Clean Code in MVC context

Pratima
HighApe Tech
Published in
7 min readSep 15, 2018

“Take a left, go straight and take the second right. You will find a hospital to your right, then take the left, left again, once you spot the tree to your right……..” Wait, what?!

Now, take a look at the images below. Which of them would you double tap on insta and heart on facebook?

Most of us would prefer the image on the right over the one on the left.

While the directions in the above example are grammatically correct, they are quite clumsy and mixed up. Information is hard to grasp when the language used lacks clarity.

Here’s what messy means in the coding jargon:

In layman’s term, messy just means disorganised. And in the context of coding, it means pretty much that. Complex, confusing, disorganised; ultimately, difficult to work with.

Clean, on the other hand:

The exact opposite of that. Legible, and therefore, easy to work with.

Now that you’ve been introduced to a few words in the coding realm, let me share my story with you. The story of how I transitioned from writing messy code to clean code, and why I suggest you do the same.

Programming/Coding is a way of conveying your orders to the computer. Grammatical errors can be overlooked but clearing out the junk and polishing what needs sparkle is extremely important.

Story Time!

When I started to work as a professional developer, I didn’t have a lot of idea about the code’s layout. My coding was limited to getting my machine do my work effectively, and I was content with it.

It so happened that I completed my tasks a little ahead of schedule one Friday evening. Naturally, I rushed home to cool off with friends, my mind far away from the bulky codes I’d left behind.

Unfortunately, a small bug surfaced on Monday morning. I went through my code to shoot that bug, and it was hard for me to figure out where I’d lost my way.

I could not decipher my own code — indeed, I had dug my own grave! I won’t even get into the details of what was happening in the controller or in the model or the view files!

I was too afraid to remove any lines of code, because I was afraid that on Friday evening I must have put them there for some reason!

It was then that I realised the importance of clean code, which went on to save a lot of my time and energy, as it has done for many other programmers.

Lets talk code now

While working on MVC framework, we somehow mix up the purpose of using the framework itself. According to my gurus– stackoverflow, quora etc, Models in MVC are to be used for fetching data from DB, Controllers to handle the logic part, Blade files to represent the design to the world and so on. But when it comes to completing the task on time, we often fail, because we mess up by writing dirty codes which will be a haystack later.

A number of hacks have come in handy. To narrow it down, here are four things that have helped me the most:

1. Variable/method/classes naming:

Naming a child (variables/classes etc) is crucial because the child will be recognized in their whole life (through out the project) by that very name. Say, I need to declare 3 variables so I go with

variables => $cake1, $cake2, $cake3

Wow, I have 3 cakes, God save me from diabetes…ummm..bad joke, my bad. You cannot figure out much from these names. Good naming would be,

variables => $tea_cake, $birthday_cake, $anniversary_cake

Cool, right? The names themself speak for the purpose of the cake. Same goes for class names and method (function) names. Consider

function names => get_me_car()buy_me_car()

This is ambiguous. So I would improvise on it, like:

function names => book_my_cab()buy_me_mercedes()

Clearer, isn’t it? Same goes with “Class namings”. Dont be afraid to be a little verbose with your names, if required. Clarity precedes wordiness.

2. Formatting code:

Let the books be at the edge of the table, let the shoes be clean, let the food spilled on floor be cleaned.

Taking few cues from the above example, programatically, it would be elegant if I,

⦁ give one space before and after ‘=’ (operators) in logic part

⦁ space for ‘{‘ after function name, or the curly braces can go for next line.

⦁ consistent indentation — by making sure for loop and if statements start and end at the same indentation with equal spaces.

⦁ Equal lines of break between two functions.

⦁ Equal spaces for new line of code, I prefer 4 spaces (i.e 1 tab)

⦁ Character limit per line (80 as standard)

⦁ Classes with minimum lines, doing its job in best way.

⦁ Grouping up declaration of function, defining them and placing them at different places.

⦁ Better to avoid “Deep nesting” — feels dizzy :(

⦁ Using either “snake_case” or “CamelCase” throughout the project.

There are many more standards you can follow, but the above mentioned points are a few good ones to start with.

3. Small functions with one task — Going modular:

In the same way, functions(methods) can be chunks for clear task and reusability.

Consider this example :-

I have written two functions, which does almost the same work. That means 4 lines of extra code, memory wastage for variables, extra consumption of my time and effort.

And if I needed a function which is slightly different but does the same thing, should I write one more function?

That was what I did earlier. I forgot which function was responsible for which task, so I was too afraid to delete any function and unable to find the bug.

Simple Solution:

To simplify a messed up code, I summarized the function. This proved to be helpful in recycling the code.

Clean Code:

Much clear and simple right ???

So , I just wrote a basic function “get_it_done” which would handle the task based on parameters passed to it. And when I need to get a similar kind of work done, I can just alter the same function to suit my need.

4. Comments for clarification:

This is one not for computers, but for us. It is believed that the best codes don’t require commenting as the code speak for itself.

I comment my codes at points where the logic applied is complex, or at the starting of the file to explain why it was created. It is a good practice because when other developers are looking at your code, they will be able to understand it easily.

But brush a little :

It would be better if I remove the lines which are commented — maybe variable declared and not used, some logic used earlier, conditions applied for DB queries but not used in the later steps of the program.

It is necessary for the clarity of other developers. So, make sure you remove unwanted codes.

Forward Clean Code also includes “File and Folder Organization”. I use Visual Studio Code while working on Laravel. Laravel is already structured to place Controllers, Models, Blade, Images etc files separately. But when I come across a task where multiple things need to be done, I prefer to organize the files having tasks separately.

Say, for example, at highape.com, when a user logs in/registers, I need to check if he is a new user or an old user. In case he is a new user, I need to capture all his details in our SQL database and send him a welcome email. In case, he is an old user, I need to check if he has updated his information, if yes, I need to update that in our SQL db.

So, instead of writing all things in one controller, I broke down things as follows :-

check if new user -> update and send mailcheck if old user -> did he update any detail? -> No -> Move aheadcheck if old user -> did he update any detail? -> Yes -> Update Detail

Flowchart representation of the use case (Chart only moves downwards)

So, the task of sending an email (which is different than updating the details) was written in a different file, under a folder call ‘Jobs” (whose only job is to send mail).

This made my code smaller and independent, and “Jobs” can be used again when I need to send mail (Reusability).

Wrapping up:

Practicing clean code has many benefits: its easier to start and continue, easier to follow, understand and update. Most importantly, it feels great to see your codes tidy and work well. That in itself is worth the effort!

These were only basics for clean coding, there is so much more which we can adopt. With this, you can all jump off my train of thought, for now. I hope this article was useful to you. Thank you for reading!

You can also connect with me on LinkedIn and follow me on GitHub.

Happy Coding :)

--

--