Art of Clean Code

Write code that can be read like a story.

Mohit Gupta
Dev Genius

--

Pixabay

If someone asks me who is my Guru for Java, I would say ‘Sun Microsystem’ and ‘Apache Foundation’.

I am from a generation, where most of the programming learning was by reading Java source code. Internet was not a big store of many rich blogs or forums, and hence reading through code was the best resource to learn. Moreover, the kind of components we built, was not possible without understanding the behavior of the system that we were extending. Hence reading through the code of Java libraries and components was almost mandatory for building the right extension, and the products.

One notable thing, I still admire about the source code of Java and Apache kind of products is the clarity of code constructs and rich documentation, code which speaks its intention very clearly. That made the code reading experience enjoyable and easy like a storybook. Code was written and documented so beautifully, I am sure that anyone can understand that code easily, even two decades later now in the future too.

Much of the credit of reading such a large codebase was to that effective coding and documentation style, which developers followed to write that code.

Fast forward today, we are in an era where doing more by writing lesser code is sought after style. With the availability of functional language, many abstract language constructs, and lambada expression kind of support, it makes all the sense and makes code less bulky too.

Yesterday or today, then or now, basic principles of writing clean code are the same and are required equally. Ultimately it is all about the art of writing readable code, a code that speaks of its intention clearly, where it is hard for bugs to hide, a code that can tell about any dysfunction loudly, a code that can be read easily by co-workers or by anyone later in future too without spinning their head.

What is clean code

Any fool can write code that a computer can understand. Good programmers write code that humans can understand — Martin Fowler

  • A code that can be read easily by anyone and everyone, not only by its author.
  • A code that speaks of its intention clearly
  • A code where it is hard for bugs to hide
  • A code that can tell about any dysfunction in the system loudly itself

Let us talk in brief about some of the key enabler principles for clean code.

Meaningful Names which Reveals Intention

If I need to choose one most important thing for clean code, I will pick this. That is its importance for code readability and maintainability.

Picking the right name, which can reveal its intention of existence clearly, is very important. It takes time to pick the right name, however, that effort and time are worth it as it could save hours of effort later to understand the code or any issue.

Simple thumb rule, as soon as one reads the name of a class or variable, or function, it should tell loudly ‘Why I exist’. This rule applies to names of Package, Class, Variable, Function, database tables, columns, property files, properties everything. Even the name of the iterator variable in for loop is equally important to keep code readable.

If any code is not able to reflect its intention just by name, due to any reason or complexity, it makes all sense to add documentation to make it easy for the readers.

Few pointers

  1. Use pronounceable names. Use the full descriptive name, rather than the acronym which needs a dictionary later. Ex: ctrlGpForPt > controlGroupforPatients.
  2. Don’t be afraid of long descriptive names if it makes reading easy. Let VM, compiler, IDE handle lengths for us.
  3. Avoid confusing names for similar constructs, make clear distinctions. Ex: accountActivation, accountActivated < has a high potential of confusion while reading the code.
  4. Use the same pattern for similar operations. Ex: getRecords to get data from the database, instead of using the get, fetch, retrieve at different places.
  5. Use domain names as much as possible, as it helps readers later to make sense of code quickly as long as they understand the product domain. Ex: jobProcQueue > accountProcessorQueue.

Names should make the reading of code simple, rather than a need to juggle with multiple names and construct relations in mind for readers.

Keep Length of Constructs in Check

It could be asked that what’s in length if names are good, and code is clean. However, the length of implementation for any construct defines the complexity for readers. The human mind can keep limited complexity and data in memory at a time. The more we add to this, the more it demands to juggle with memorizing and cross-referencing.

The solution is to keep length in check for classes and functions. The easiest approach is, if there is some code doing related work, bundle it in a separate function and call. Reading a function of 15 lines with 5 function calls of the meaningful name is much easier than reading and understanding a function of 100 lines.

Hence, break the implementation into multiple smaller functions with meaningful names.

Keep it smaller than small!

Principle of Single Responsibility

This is not only the architecture principle (Read more here), but equally applicable to the low-level design, function implementation, and code readability also.

We started this article with the principle that names should reveal the intention. How is that possible if a function or class is carrying multiple responsibilities?

If any class or function is serving more than one intent, break it further.

No Side Effect Code

It is an extension of the previous point.

A code should do what it is supposed to do. Nothing more, nothing less.

Ex: Login function should check the authentication, may check and initialize the information for authorization. But, it should not initialize the JSON structure for UI Rendering. That will be like crossing the concerns, which defeat the Principle of Single Responsibility and clear intentions both.

Have Same Code Format in a Product

How would you feel about reading a book which has 10 different fonts, indentation, and color styles in 10 chapters? Not comfortable surely. The same is with code. Having the same format across the classes, packages, modules makes it easy to read the code.

Solution: Define formatting rules with the team, and follow it everywhere. It is one of the easiest things to implement by agreeing and defining a common code formating config that is used by all developers in IDE.

Length of a Line

Does it matter…..?

Yes, it matters a lot. The length of the line should be set according to the normally used monitor’s width. It was fine to have 40 or 80 line length earlier with a smaller screen, but now with wider screen monitors, it makes all sense to have it at least 120 as standard.

It makes code readable by keeping contents in the same line, rather than reading multiple lines. Visualize reading a function name with few parameters in 3 lines, versus in one line.

Keep Related Code next to each other — Better Top Down

Although finding function is easy with IDE shortcuts. However, reading should be easy just by mouse scroll also in a class. Hence, it is advisable to keep related codes next to each other and better in a top-down format where readers can start from the top and keep following the next methods down similar to reading the book.

One step closer to writing code that can be read like a storybook!

Assert if something is not as Expected

Assertions (or alerts) are not only to just check parameters. These are powerful tools to validate the behavior of the system when no one is looking at it.

Don’t we expect our car to tell if engine oil or coolant is less? Or if there is some impurity in fuel. Why, because it makes our life easy by taking proactive action timely that also without spending hours to understand the reason before the car breaks down.

The same is true for Software Systems too. A system should tell if something is not correct in it. Tastefully designed assertions (+ monitoring, alerting) can make developers' life much easier by shouting erroneous conditions before these become a big issue, like corruption of whole data in the system.

Hence, spend quality time designing assertions and alerts in your code. And before that, define a standard to log and report these assertions.

A self-validating system (code) is the best system!

Summary

For a software developer, code is what a painting would be for a painter.

Write code that can be read like a story even by a new book reader, a new member of the team. Write code that is agile enough to be extended easily for any new features or improvements. Write code that is empathetic for other developers, and is easily maintainable for years to come.

Write code like a storybook, which every reader loves to read.

Happy Learning, Happy Coding!

Next

There are more aspects of clean and maintainable code, which are Error Handling, Logging, Tests for Self-validating Systems, and Documentation. We shall cover these in future articles.

Art of Clean Code — Error Handling. Refer here

Art of Clean Code — Documentation. Refer here

Art of Clean Code — Logging. Refer here

If you have any suggestions, feel free to reach me on Linkedin: Mohit Gupta

--

--

Enjoy building great teams and products. Sharing my experience in software development, personal development, and leadership