Writing Cleaner Code Part 1 – Tips on Writing Code that will Make Life Easier for Everybody
computer repair concept - workers repairing keyboard

Writing Cleaner Code Part 1 – Tips on Writing Code that will Make Life Easier for Everybody

“Any fool can write code that a computer can understand. Good programmers write code that humans can understand.”

— Martin Fowler

 

Imagine this:

It’s another normal day in your neighborhood, and you go outside to get the mail from your mailbox. You casually flip through all the boring old junk mail and suddenly your attention falls on one brightly colored envelope.

“CONGRATULATIONS!” it screams on the cover.

Turns out, you won that sweepstakes you entered a week ago, and before you know it you’ve been flown to Silicon Valley and getting toured through Microsoft’s luxurious headquarters. To your surprise, you don’t hear that much keyboard pitter-patter as you expected, and most of the developers are just starting at their screens, reading and scrolling.

 

Programmers Read a Lot

It may surprise you, but being a programmer isn’t all about writing code. Not by a long shot.

There’s a lot of other things involved – meetings, brainstorming sessions, designing, drawing diagrams, debating efficiency systems…

As a matter of fact, a whole ton of your time will be used reading code rather than writing it. You’ll be hunting for bugs, updating old algorithms, looking into open-source projects, and lots of stuff like that.

So you won’t be writing all that much, actually.

With this in mind, it’s really important that programmers learn how to program cleanly. Cleaner code is harder to write, sure, but it makes life way easier since the original programmer and future programmers will both be able to understand, maintain and improve the code much faster and easier.

Come to think of it, being able to write clean code is actually considered extremely important in the programming world. If you can’t write clean code, it’ll be hard to be considered as a respectable programmer.

Now then, there are lots of ways that code can be made cleaner, and it takes a long time to make writing wholly clean code a habit, but here I’m going to give some universal tips that will instantly make your code a lot cleaner and set you on the right track to making you a better programmer.

 

  1. Give Variables Real Names

For me, this is one of the most important things to master.

And it’s the thing that pisses people off the most if not done properly.

Variables have to have proper names that make their function in the program self-explanatory. It’s very frustrating and confusing for any programmer to have to deal with a program that has variable names like a or mxlvl. It just makes the program ridiculously difficult to understand.

Just imagine your confusion if you see this while updating your friend’s skating game:

if (spd>= spml){
    srlvl = 100;
}else{
    srlvl = mrlvl;
}

This code is functional and probably perfectly efficient, but it’s still terribly written because we have no idea what it’s doing.

I can understand some programmers wanting to do this because they don’t want to end up typing “long” variable names all the time, but it’s not a good enough excuse (especially with all those auto-correcting IDEs around nowadays). Even the original programmer will find it easier to write code if he uses proper variable names.

Now look at the same code with real variable names:

if (skatingSpeed >= speedMilestone){
    skaterRespectLvl = 100;
}else{
    skaterRespectLvl = minRespectLvl;
}

Now that’s a real beauty.

Usually, variables are named using camel case (every word except the first one is capitalized, as seen above) or underscores (like typing skating_speed instead of skatingSpeed).

 


  1. Wondrous Whitespace

Just like how books have paragraphs and indentations, so should good clean code. A little indentation and empty lines can do wonders. Just as an example, look at the code we used before without indentations:

if (skatingSpeed >= speedMilestone){
skaterRespectLvl = 100;
}else{
skaterRespectLvl = minRespectLvl;
}

 

Not very attractive.

Be sure to indent loops and decisions, and leave empty lines between chunks of related lines of code. For example: leave a line between a chunk of code that plays an endgame animations and a chunk that loads a new game level.

When declaring variables, leave a line between variables that are related. For example: a game, leave a line between a bunch of lines that declare all the health variables and a chunk that declared all the attack variables.

 


  1. Comments

Don’t make the mistake of thinking that comments are unnecessary!

When I started programming for the first time, I hated the idea of comments – they seemed to me that they were only meant for people with pretty weak memories. I saw no point in explaining something that seemed so obvious to me at the time.

Now I can’t do without ‘em.

If you’re new to programming, you may also think that commenting is superfluous or unnecessary, but that’s far from the truth!

Comments make it way way faster to skim over code and understand its functionality and reasoning. It saves a ton of time and, honestly, they aren’t that troubling to write.

Besides, no matter how good your memory is, you’ll most likely forget what an old piece of code does or how it works after a few months of writing it – and comments will really save you in times like this.

 

Don’t overcomment though!

Don’t comment absolutely everything – your code should be self-explanitory enough to survive not everything being commented. Instead, comment over chunks of code separated by whitespaces. Mention to what those chunks do and, more importantly, why they’re there.

Give warnings like “Be careful when changing this code. Altering X may greatly affect Y”

Give explanations like “Y was added to do this that and this” or “I needed this to prevent that.”

These explanations will prevent future readers from wasting time trying to understand your logic from thin air because it’ll be right in front of them.

 

No more Captain Obvious

Okay, those first three points were the more obvious of clean code principles, but there are some others. Please don’t try and get the hang of only those first three, these nuances are important too!

Atomic Methods

In programming, an atomic method is a method that completes only one task. The task needn’t be a simple task per se, but it has to be a single task.

For example: a method that both safely kills and resurrects a player is not atomic. Those actions should be in their own functions/methods.

When programming, you should try and keep your methods atomic. If you see that a method is achieving more than one discrete objective, it’s not really being atomic. It can do smaller tasks that lead up to one objective, but the important number here is one.

Keep in mind that you can make an atomic method made of other atomic methods. For example: a die() method that’s made of a stopBreathing() and a fallDramatically() method.

There are some good reasons for making methods atomic:

First of all, atomic methods make code easier to trace. Provided that you’ve named your methods well, anyone whose tracing your software knows exactly what a method is doing, and doesn’t have to worry about any side effects (additional objectives that an atomic method shouldn’t be achieving).

Secondly, methods become more reusable since they carry out simple tasks. Simple tasks are always easier to layer on top of each other than complex ones.

Lastly, atomic code makes code easier to alter, since the methods are more predictable. You don’t have those pesky side effects hiding in there that could spring up and cause some unforeseen trouble. Everything is nice and predictable – like good code should be.

 

Segregate!

Walking direction on asphalt

This is more for Object-Oriented Programming (abbreviated as OOP) and Web Development (sorry everyone else!). I use Object Oriented languages, so I’ll take it form the vein of OO.

Although segregation is a real problem in real life (with all those inhospitable people out there and whatnot), lack of it thereof in programming is also a real issue.

In programming, big problems are best tackled by breaking them down into smaller problems, which are then solved individually by mini programs (like classes in OOP).

At the end of the day, all those mini programs brings their small solutions together an “WHAM!” – the big problem is solved.

This approach makes programs more comprehensible and, just like atomic methods, makes classes more reusable and hence useful.

It also makes code more manageable and maintainable. Bill Spooner from Pluralsight gives a nice and punny example of this:

“A good example might be when classes are all loading in file resources themselves — the code can be messy, and if you want to change how resources are managed, you have to change it everywhere. In this case, creating a ResourceManager class with a getResourceByName() function could be a clean and elegant way to make that functionality a bit classier.”

Segregating code into classes also prevents making a dreaded God Object – a class that simply does too much and a class that too many other classes depend on. Such classes are usually overly complex and confusing and…well…are just a blatant pain to deal with.

Calling it a Day

This ends part one of Writing Cleaner Code. I hope you’ve been able to take something await from this post. In part two, we’ll tackle some more specific and technical tips. Till then, happy coding and happy cleaning.

Look at other cleaning tips by reading up on these links:

https://en.wikipedia.org/wiki/Code_smell

https://www.harding.edu/fmccown/writingcleancode.pdf

http://www.makeuseof.com/tag/10-tips-writing-cleaner-better-code/

 Photo Credit: TeePublic, The Content Wrangler, The Bobby Pen

Anderson

The owner of the Loading Developer blog and the Lumberjack Apps studio.

This Post Has 2 Comments

  1. Femi

    Great Job! Thanks for taking time to share your knowledge! Keep up the great work!

    1. Anderson

      Thanks for reading! Be sure to share it with others too!

Leave a Reply