How to write cleaner code…

Divyanshu
tech@iiit-gwalior
Published in
5 min readMay 26, 2020

“Simple and Readable code is far better than Complex and Clever code.”

When freshly starting with learning to write programs, it is elementary to develop bad habits. These bad habits can affect your process of writing code and debugging it.

We spend much more time reading code than writing it, even if it was us who wrote it in the first place. Thus, it is essential that the code we write is appropriately formatted, and is consistent throughout the project.

Following are some ways to write cleaner code:-

1) Naming Conventions

  • Use descriptive names;
  • Use short names; Be consistent;
  • Variables, functions, objects;
  • Every entity in our code is referred-to with a “name”.

a) Descriptive

Names are crucial to us, so it is only natural for us to put some thoughts into them.

> int a, b, c; // impossible to tell what these variables are for

> int health, attackDMG, speed; // now, it is clear

Usually, names are structured like so:

> int noun; // variable stores something

> int adjectiveNoun; // variables store something with a certain property

> int verb(); // function does something

> int verbNoun(); // function does something on something

b) Short

It is easy to fall in a trap of writing overly-descriptive names.

As a rule of thumb, names must be the smallest combination of, at most three, `words`.

> int sanitizeAndAddUser(Data data); // Too long

It is a much better idea to make too different functions.

> Data sanitize(Data data); // shorter

> int addUser(Data data); // and refactored

c) Consistent Casing

Above, I wrote “smallest combination of words”. That was not a typo. Names must be composed of words. But names can’t have spaces so that the words would get cluttered.

> char currenttoken; // this is very hard to read

Try to use a different type of casings to eliminate such a problem. One such casing is camel Casing.

> char currentToken; // first letter of every other word is upperCase

There are a handful of such casing rules;

Namely: camelCase, snake_case, kebab-case, UpperCamelCase;

No matter what casing one decides to use, it is crucial to be consistent with it throughout the codeBase.

2) Visual Structure (AKA Indentations)

  • Align curly braces;
  • Indent each scope depth;

This includes:-

i) Putting braces in an inconsistent or disorganized fashion.

ii) Not using consistent indentation depth, or lacking them all together.

(Quite often, programmers, who are new to programming, tend to clutter up their code. )

a) Braces

Many programming languages use curly braces ‘ {} ‘ for describing scope bounds. Which implies a program’s logical scoping maps, almost, directly to code’s lexical scoping.

As with casing, There are quite some BracesPlacementStyles AKA IndentationStyles.

Follow this link to find an Exhaustive list of style: https://en.wikipedia.org/wiki/Indentation_style.

As for an example

1> int i; //it is okay use i for iterator

2> for (i = 0; i < 5; i++) {

3> //statements

4> } // notice this brace matches up with the for keyword

b) Using proper Indentation-Depth

Notice how, in the previous example code[Line:3], whitespace is to represent depth.

It allows, us to group statements of same depth together; and reader to comprehend statement easily.

3) Commenting

Use Helping comments;

Every programming language provides us with syntax to write comments in our code. It is an integral part of any given language, as this allows us to provide hints for the reader about what a piece of code does.

Often one writes some piece of code and gets side-tracked for weeks or just days.

When they come back to the previous code, they have no idea what that piece of code does. It is ubiquitous, so we mustn’t be embarrassed if it ever happens.

But to avoid such conditions all together it is a good idea to add comments to our code.

1> // Connects to a socket

2> // returns error status

3> int sockConnect(Socket* sock) {

4> //complex logic

5> }

4) Avoid unnecessary Comments

Don’t comment on things that are obvious from context;

Adding useless comments to code will bloat the code and make it harder to read — opposite of what we desire.

For Example, in the previous example code;

It is clear from the context and the function’s name `sockConnect` that it makes a socket connection. So the comment on line one can be removed.

The second comment is still required because the function syntactically returns an `int` but semantically returns Error Status.

We can avoid this comment by creating a type alias as such:

> typedef int ErrStatus

which can then be used in the definition as such:

> ErrStatus sockConnect(Socket* sock) {

It allows our code to be much more expressive.

5) Modularize

  • Break the problem into parts;
  • Use modules to contain each solution;

Most programming languages provide us with some tools to modularize our code.

These tools may include- Functions, Objects, Modules, Packages, Namespaces, etc. Making use of these tools allows us to declutter our logic, and separate them in maintainable and testable units.

When modularized, every logically complete unit will stand out visually in our code. Also, this will break down our large monolithic functions which perform way too many tasks to keep track of.

As an example, let’s consider the problem of accumulating elements of an array. Let’s assume we are required to input, compute and output the array.

It is easy to kick up a `main` function with these actions performed in sequence. Preferably, we can use some comments to separate these comments.

But a better approach would be to separate these actions into units like so:

1> void arrFeed(int* arr, int size);

2> int arrSum(int* arr, int size);

3> void arrDisplay(int* arr, int size);

Now `main` would only show a declaration of array and size and calls to three descriptive functions. The above code expresses the intention that we had in the first place.

EndNote

Always use a space after the comma, It is easy to write code that smells, and it is easy to get into bad habits, but in the long term, they only hinder in the development process. Other people read our code; be it ourselves,

We must write code that follows the community guidelines and conventions.

But just in case you desire to learn how to write unmaintainable code, here is a good read: https://www.mindprod.com/jgloss/unmain.html.

Cheers, happy coding!

--

--