Five Steps to Cleaner, Clearer Code

UPDATE 7/7/15: I'm happy to say that this post was recently promoted on LinkedIn's Pulse and generated a ton of feedback. I've included some additional thoughts at the end of this post.

I firmly believe that clear code reflects a clear mind.

Messy code is at best unpleasant and at worst near impossible to read. If you are working with friends or coworkers, you will drive them up the wall with unorganized code.

Even if you are the sole programmer on a project, writing clean code will make it easier for you to read your own work later. This is particularly handy if you are working on multiple projects or haven't looked at your files in a few days. Organized code can also help you streamline what you've written. You'll find it easier to identify redundancies and combine and reuse code.

Of course, working code is far superior to clean code. But if you have an hour, follow the five steps below to clean up your files. Your future self will thank you for it.

1.  Understand how data moves through your application.

You should have an understanding of all the data and relationships in your program. You should know how data moves around your app/site through flows and processes. Having a clear model can make it easier for you to understand how your code should be written.

This is my initial model for Leder. Ideally, you should update your model throughout the course of your project development.


2.  Write thoughtful comments.

Commenting your code is a must. Make sure you strike a balance between writing too much and too little—comments ought to be thorough and useful, but too many can actually impede's one's ability to read and understand your code. My personal rule of thumb: Is my code as written self-explanatory to a beginning programmer? If not, I comment.

Here's an example of comments I wrote to explain a section of Leder that iterates through an array of strings, and changes the attribute "isHighlighted" to true if the current string meets certain parameters.

//iterate through each object in $scope.words
for (var i = 0; i < $scope.words.length; i++){
    //if current element is greater than the ID of the first word and less than the ID of the last word, then change isHighlighted attribute to true
    if ($scope.words[i].id >= firstWordID && $scope.words[i].id <= lastWordID) {
        $scope.words[i].isHighlighted = true;
//ensure CSS highlighting reflects changed attribute
//set highlight mode to false so a new touch can register
$scope.highlightMode = false;

3.  Indent your code.

This is a stylistic tip. Code that is clearly indented is much easier to skim and debug. A basic guideline is to line up opening and closing tags, and further indent interior code. Tools like JSLint can help you do this in an automated way. Take a look at the code sample below to see what I mean.

for (var i = 0; i < $scope.words.length; i++){
    //if isHighlighted attribute is true, set it to false 
    if ($scope.words[i].isHighlighted){
        $scope.words[i].isHighlighted = false;

4.  Group like-minded functions together.

Group similar functions together if possible. You can separate chunks of code with spaces to make them more readable.

5.  Finally, be consistent in naming.

I usually write my variables as nouns and functions as verbs. Whatever your style, be consistent in your naming scheme.

Advanced Tip

Small websites and apps do not require a complex file structure. In those cases, one folder each for HTML, CSS, JavaScript, and images is usually sufficient. If your code is becoming too large and unruly, however, rethinking your file structure may be a good idea. My next post explains how I did that recently for Leder


UPDATE 7/7/15:

Whenever I get thoughtful, interesting comments, I try to respond to them. Here are two particularly insightful comments as well as my responses, reposted from LinkedIn:

From Adrien Hupond:  You might be interested in MVVM. It's most useful for desktop application, but can be great for some data-centric applications with RESTful services for data persistence and a client-side JS application based on a MVVM library such as Knockout JS. There are other alternatives to MVC which still is a nice pattern to implement. What's important in my opinion, is about knowing pros and cons of each pattern so you know how to select the most suited one for your application, instead of reusing the same one even when it is no help. Your advice about thoughtful comments is great but examples are bit underdoing it. Commenting is not about describing your code but the reason why you wrote it. Writing about the next line is iterating an array has few added value before a foreach statement : one easily understands that a foreach iterates over a collection. What would have been interesting is about why you need to iterate over that collection. For instance : « highlight all matching words ». Likely, « if isHighlighted is true then set to false » has little value in comparison to some « remove all highlighting from words » before the iteration. Most programs source code are full of « // Why do we even wrote that line ? » and « // Dunno why, but if you remove the next line, the program will crash ». Keep up the good work though, you're on a good way :)

My Response:  These are great suggestions, Adrien. I really like your point about knowing the pros and cons of different architectural patterns in deciding what works best. My MVC pattern is definitely influenced by the frameworks I chose to use, and I must admit I did not consider patterns as a key factor in my decision (opted for ease of use, complexity, built-in features, fit with my app, etc). I am certainly more critical now. Good point on comments too. I should have clarified that comments serve different purposes based on who the audience is. In the example I posted, the comments were just for me, meant to provide a skimmable summary in lieu of reading the actual code, so I tailored them to my personal style. But yes, in cases with multiple authors especially, I agree with your point that comments that focus on the reason WHY the code exists are more useful.

From Rey Malahay:  Great article, Sanette. Except for one thing, your diagram illustrating the MVC (Model View Controller) is wrong. There is supposed to be NO direct interaction between the Model and the View. It is supposed to be the Controller that updates the View on the Model's behalf...

My Response:  Good point, Rey. The model should not know about the view. The diagram I used was perhaps a bit unclear, but it is meant to show a flow of data rather than direct manipulation, i.e., updates from the model are reflected in the view. In many MVC frameworks, it's common for views to update themselves based on changes in the model.


Finally, a few people mentioned these tips are beginner-level stuff. What I have to say to that is—great! They're supposed to be