Using clean code principles for better code

Good Housekeeping

© Lead Image © donatas1205, 123RF.com

© Lead Image © donatas1205, 123RF.com

Article from Issue 264/2022
Author(s):

Clean code principles can improve the readability of your source code, making life easier for both you and your users.

Clean code is a set of rules and procedures that make it easier to read and understand source code regardless of the programming language used. Many clean code strategies fit all languages, but some more far-reaching strategies only prove useful in the object-oriented world. The clean code concept is not new or revolutionary. Back in 2008, Robert C. Martin described the procedures in his book, Clean Code: A Handbook of Agile Software Craftsmanship [1].

With today's highly complex IT applications, ensuring that source code has a clean structure has becoming increasingly important. The clean code concept has evolved in recent years, and the procedures described in Martin's book have been expanded. To get you started writing cleaner code, I'll describe some of the core ideas and rules of clean code.

The Scout's Rule

"Always leave code cleaner than you found it." If you take this rule to heart, a project's source code will get better and better over time. You don't need to be afraid of breaking something, because the previous version can always be restored thanks to the version management (i.e., Git). Modern IDEs also provide many tools for reengineering code. Renaming classes or methods doesn't pose so much of a risk anymore.

Typically, the compiler doesn't care what names you assign the individual program components. Whether you use uppercase as opposed to lowercase or underscore instead of CamelCase, as long as the name fits together somehow, the compiler will build an executable program.

However, this freestyle kind of code can be extremely difficult to read. Instead, you should to stick to the style conventions that apply to the programming language being used. In Java, for example, class names should always start with an uppercase letter, while methods should start with a lowercase letter. Modern IDEs usually have a feature to automatically format source code: You should definitely use this. If several people are working on a project, they need to agree on using the same format.

Mnemonic Names

A program's components should always be given mnemonic names. This rule applies to classes, methods or functions, and variables. The names should not be too long, but they still should describe precisely what is happening.

You also need to keep in mind the variables' validity range. It is perfectly fine to follow conventions when naming the loop variables, as in, i or j. And x, y, and z are certainly the most meaningful labels for a coordinate system. But if a variable or object is used in a larger context, you should definitely give some thought to the name.

Avoid including the class name in the method names. All programmers should understand that a method always works on the object in which the method is defined. While you should always use nouns as class names because they represent entities, method names should include verbs. Ideally, avoid using abbreviations in the names; there are some exceptions to this (e.g., VAT).

While it may sound peculiar at first, make sure the names you choose are pronounceable. People will need to talk about a class in meetings or code reviews. Not having overly complex or similar sounding names will make talking about a class easier.

As a universal rule, a comment should never be necessary to explain a component's purpose. Instead, the name should speak for itself. In other words, do not use meaningless generic names such as manager, helper, handler, processor, and so on. A class is always intended for a specific purpose, so name the class for that purpose. For customer projects, make sure you use the customer's designations for the names; otherwise, misunderstandings will repeatedly occur.

Choose names to show the idea, responsibility, and limits. For instance, if you use the Model-View-Controller architectural pattern (which subdivides software into the data model, view, and program control components), then name the classes Model, View, and Controller. Additionally, include the concrete function in the name (e.g., LoginController or ContractSaveController)

Type names do not belong in method and variable names. Instead of writing

List customerList = getCustomerList

use

List customers = getCustomers

You can already tell from the type that it is a list. In addition, you should always use the same name for an entity (such as Login, User, or Account). Filler words such as to, from, and the like should be avoided.

Comments

"If the compiler understands the code, so must the developer." This rule means that comments are unnecessary. This statement, which seems somewhat short-sighted at first glance, makes perfect sense in a slightly modified form in the clean code context. If you feel the need to add a comment to a program section, you should think again about whether the code is really clean. The same applies to the names of classes, methods, and variables.

I'm not saying you can't include comments in your code anymore. Instead, comments should prompt programmers to consider rewriting a code passage in a more easily understandable way. A comment needs to describe what the developer was thinking or trying to accomplish when writing it.

On the other hand, to-do comments are allowed, assuming that somebody actually does the work. The developer can use a to-do comment while still working on the code. Strictly speaking, however, a to-do comment should never make it into the repository. If it does, it must include a specific target date for completion.

Tools such as Javadoc can be extremely useful in many cases. You can automatically generate the necessary documentation, more or less as a side effect of using the tool. However, this automatically generated documentation is only useful as long as the comments in the source code are up to date. Pay special attention to this: Almost all developers rely on up-to-date documentation.

Buy this article as PDF

Express-Checkout as PDF
Price $2.95
(incl. VAT)

Buy Linux Magazine

SINGLE ISSUES
 
SUBSCRIPTIONS
 
TABLET & SMARTPHONE APPS
Get it on Google Play

US / Canada

Get it on Google Play

UK / Australia

Related content

  • PHP XHP Extension

    The PHP XHP extension lets you use HTML and XML tags directly in the PHP code.

  • JavaScript Alternatives

    JavaScript is the stuff of which many interactive web clients is made, but it comes with a fair amount of historical ballast. The creators of four alternative scripting languages seek to ditch the ballast.

  • Kotlin Programming Language

    Kotlin, a small island in the Gulf of Finland, is also the name of a new programming language that aims to become a modern alternative to Java.

  • Rails Framework

    Most web libraries make 90 percent of the job simple and the rest impossible. Rails,an open source framework programmed in Ruby,is flexible enough to succeed with that remaining 10 percent.

  • Embedded Rust

    Rust, a potential successor to C/C++, claims to solve some memory safety issues while maintaining high performance. We look at Rust on embedded systems, where memory safety, concurrency, and security are equally important.

comments powered by Disqus
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters

Support Our Work

Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.

Learn More

News