paint-brush
How to Make Your Code CLEAN and BEAUTIFULby@rsrajan1
42,778 reads
42,778 reads

How to Make Your Code CLEAN and BEAUTIFUL

by Ravi Shankar RajanJanuary 21st, 2018
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Robert Martin nailed it to perfection when he said.

People Mentioned

Mention Thumbnail

Company Mentioned

Mention Thumbnail

Coin Mentioned

Mention Thumbnail
featured image - How to Make Your Code CLEAN and BEAUTIFUL
Ravi Shankar Rajan HackerNoon profile picture

And it is the ONLY way to GO FAST and meet the DEADLINE.

Robert Martin nailed it to perfection when he said.

“The only valid measurement of code quality is What-The-F**ks/Minute.”

Let me explain a bit further.

Whenever I do code review, my mind churns out three distinct emotions.

· What-the-F**k (in disgust) — This code is not required.

· What-the-F**k (in admiration)- This guy is smart

· What-the-F**k (in exasperation) — unable to understand this gibberish

So what is the very first thing that influences us whenever we see any code?

It is Clean and Beautifully written code.

And writing clean and beautiful code is the mark of a GREAT software craftsman.

There are two parts involved in learning this great craftsmanship- Knowledge and Work. Knowledge teaches you the patterns, principles, practices, and heuristics that you need to be better in your profession. But this knowledge needs to be ground into your fingers, eyes, and gut by constant practice and hard work.

So in a nutshell, learning to write clean code is hard work. You must sweat over it. You must practice, stumble, fail and master and repeat the steps again and again till you get it right. There is no easier way or trick to go about it.

And here are some of the ways in which you can master the art of writing clean and beautiful code.

“What is in a NAME”

Kendrick Lamar nailed it when he said.

“If I’m gonna tell a real story, I’m gonna start with my name

Names are everywhere in software. We name our functions, classes, arguments, packages and what not. We name source files and the directories and everything within that. We name, name and name continuously and thus it becomes the most important clog in our engine of clean code.

Your name should reveal the intent. Choosing good names take time but saves more than it takes when the going gets tough. So take care with your names and change them when you find better names. Everybody who reads your code will thank you immensely for it.

Always remember, the name of any variable, function or class should answer three big questions; why it exists, what it does and what it is used.

This not only requires good descriptive skills but also a shared cultural background that transcends across boundaries and no one can teach you this better than you yourself.

“Functions should DO ONLY ONE THING.”

Louis Sullivan once beautifully said.

“Form follows function.”

Every system is built from a domain-specific language which is designed by the programmers to describe it aptly. Functions are the verbs of that language and classes are the nouns. Functions are usually the first line of organization in any programming language and writing them well is the essence of writing good code.

There are only two golden rules for writing clean functions:

· They should be small

· They should do only one thing and they should do it well

So this means that your function should not be large enough to hold nested structures. Therefore, the indent level of a function should not be greater than one or two. This technique makes it easier to read, understand and digest. In addition to this, we also need to make sure that the statements within our function are all at the same level of abstraction.

Mixing levels of abstraction within a function is always very confusing and leads to unmanageable code in due course of time. Master programmers think of functions as stories to be told rather than code to be written.

They use the facilities of their chosen programming language to construct a richer, expressive and cleaner coding block which can act as a perfect storyteller.

“Comments do not make up for bad code”

Venus Williams hit it bang on the nail when she observed.

“Everyone makes their own comments. That’s how rumors get started.”

Comments are like a double-edged knife. Nothing can be more helpful than a well-placed comment. On the other hand, nothing can clutter up more than frivolous, useless comments that consume space. And nothing can be more damaging than comments that spread disinformation and lies.

So in short, comments are at best a necessary evil. Why? not always but most of the times. The older the comment, the more difficult it becomes to maintain them and most programmers have a notorious reputation for not maintaining them in line with their code.

Code moves and evolves. Chunks of code move here and here; comments don’t and that becomes the problem!

Always remember clear and expressive code with few comments is far superior to cluttered and complex code with lots of comments. Don’t waste time in explaining the mess you have created, rather devote time to clear that mess.

“Formatting Code is always a priority”

Robert C. Martin has rightly said.

“Code formatting is about communication, and communication is the professional developer’s first order of business.”

Perhaps this above statement cannot be understated and is one of the most important characteristics of a really GREAT developer.

A formatted code is a window to your mind. We want people to be impressed by our orderliness, attention to detail and clarity of thought. But while looking at the code, if they see a scrambled, hotchpotch mass of code not having any clear beginning or end, that derails down our reputation straightway, no doubts about it!

If you are thinking that “getting it working” is the first order of business for the professional developer, you cannot be further way from the truth. The functionality you create today has a good chance of getting changed in the next release but your readability of your code will never change.

The coding style and readability continue to affect the maintainability of the code long after the original code has been completely transformed beyond recognition.

Always remember you will be remembered for your style and discipline and very rarely for the code in the future. So you need to take care that your code is nicely formatted and is governed by simple rules understood by all the team members.

Write your “try-catch-finally” statement first

Georges Canguilhem rightly observed when he said.

“To err is human, to persist in error is diabolical.”

Error handling is something which all programmers do. Inputs can be abnormal and devices can fail. As developers, we are expected to make sure that the code does what it is expected to do. However, the issue is not handling the error, the issue is handling the error in a clean readable way.

Many codes are completed dominated by error handling. And things become so scattered that it completely obliterates the purpose and the logic of the main code. When that happens it is wrong, completely wrong. Code should be clean and robust and handle errors in grace and style. That is the mark of a great software craftsman.

And of one of the ways of doing this is by proper enclosures and capture of all errors in try-catch blocks. These blocks in a way define the scope of your code. When you execute code in the try portion of the try-catch-finally statement, you are stating that execution can abort at any point of time and then resume at the catch.

For this reason, it is a good practice to start with a try-catch-finally statement when you are writing code. This helps you define what the user of the code can expect, no matter what goes wrong with code executed in the try.

Always remember that your every exception you throw should contain enough context to determine the source and the location of the error, Creative informative error messages are remembered long after the code is written and the programmers have left the organization.

Bringing it all together

So what is the single word that sums up everything here?

The answer is code-sense; the software equivalent of common sense.

According to Robert Martin, “writing clean code requires the disciplined use of myriad little techniques applied through a painfully acquired sense of “cleanliness”. These little techniques are collectively called code-sense.”

Some of us are born with it and some have to painfully acquire it through practice, persistence, and perseverance. This code sense not only helps us to differentiate between good code and bad code but it also helps us in forming strategies to transform bad code into good code.

It shows us in glaring terms that, merely baking a lovely cake is not going to help if you have used dog shit for frosting over it.

This code-sense helps the programmer to choose the best variation and the best tool available to guide him or her in his endeavor to create a value-added clean and beautiful code.

In short, a programmer with code sense is a painter who can transform a blank screen into an elegantly crafted work of art which will be remembered for years to come.

As Harold Abelson has rightly summed up.

“Programs must be written for people to read, and only incidentally for machines to execute.”

References

“A handbook of Agile Software Craftsmanship” — Robert Martin.

“A handbook of Agile estimation” — Mike Cohn

About the author-:

Ravi Rajan is a global IT program manager based out of Mumbai, India. He is also an avid blogger, Haiku poetry writer, archaeology enthusiast and history maniac. Connect with Ravi on LinkedIn, Medium and Twitter.