Thoughts about Clean Coding
Tags: cleancode, productivity, agile
Published: 2020-03-16 18:23:03

The purpose of any software project is to provide a high-quality solution for a client meeting some timetable. But sometimes it is not possible to do so because of many factors like unforeseen requirements, lack of team members and an unrealistic delivery schedule. 

Another big problem that can decrease the developer's productivity is bad-written code. As a developer, I spend a lot of my working hours reading and trying to understand what other developers had done and how I can fix their mistakes. Unfortunately, it is usual for me to find pieces of code that are so cryptic that it would be better to rewrite it from scratch. 

That kind of situation is called Technical Debt. That is the amount of rework required to correct problems created during software development by poor implementation choices, like the use of limited solutions or the lack of expressiveness on code. This sort of situation increases the software entropy, also like any form of debt, it can accumulate over time, making the proper corrections harder to implement.

## What is clean coding?

Clean coding is a development-driven philosophy that allows developers to use simple techniques to create and maintain code that is readable, effective, understandable and easily maintainable. The main focus is to decrease technical debt by creating a self-explanatory narrative that allows the introduction of changes and new features in a more natural way.

Each programmer is responsible for using and applying the clean coding rules, but the best results show up when all team members can make use of those conventions. Therefore, the whole team must compromise itself to a culture change and to the implementation of mechanisms that enforces that new coding standard.

## Clean coding techniques

In his book Clean Code: A Handbook of Agile Software Craftsmanship, Robert Martin explains the clean-coding philosophy and methods. Those are generic enough to used by any software project, despite the chosen programming language or the framework adopted.

### 1. Focus on Simplicity

Simplicity is the main point of all clean-coding philosophy. It means that the developers must avoid the use of complicated or obscure logic. Instead, they must use simple and straightforward logic. Finally, they must use well-known algorithms and coding conventions.

### 2. Significative Naming Convention

Programmers are used to creating and naming a lot of entities when writing code. They must pay attention to each language, or framework, naming convention and follow it. Also, they must avoid the use of too short, or too long identifiers. Those must be concise and simple, allowing the reader to understand its purpose without much more information.

Examples:

```dart
// Opens a certain file in reading mode

File openFileInReadingMode(String path) {
    // function body
}

// Saves a text file
void saveTextFile(String path, String text) {
    // function body
}
```

### 3. Write short functions

A function is a piece of code that is responsible for executing one well-defined task. Therefore, a programmer must avoid writing big chunks of code that perform several operations at once, but break that in some small and self-contained procedures.

Each development team is responsible for creating the naming conventions and assuring its use. But, there is some common sense that everybody can use to improve the source code readability.

- Function names must be concise and accurate. They must describe what the function does and the possible side effects. And the users must be capable of understanding the function's purpose without knowing how it works.

Examples: 

```dart
DBConnection connectToDevelopmentDB() {
    // function body
}

double calculateProductDiscount(Product product, String promoCode) {
    // function body
}
```

- Functions must have fewer arguments as possible. However, if many arguments are required, the developer must provide a configuration object instead.

Examples:
```dart

//bad example
DBConnection connectToPostgres(
    String user,
    String host,
    String password,
    String database,
    String port,
) {
    // function body
}

//good example
DBConnection connectToPostgres(DBConnectionConfig config) {
// function body
}

```

- The main goal of writing functions is to avoid duplications. So, the redundant code must be extracted to an independent function that will replace all duplicates.

Example:

```dart
User mapJsonToUser(String userJson) {
    final Map<String, dynamic> userMap = json.decode(userJson);
    return User.fromMap(userMap);
}

User createUser(Map<String, dynamic> data) async {
   final response = await MyHttpClient.post('/users', data: data);
   return mapJsonToUser(response.body);
}

User updateUser(Map<String, dynamic> data) async {
   final response = await MyHttpClient.patch('/users', data: data);
   return mapJsonToUser(response.body);
}
```

### 4. Add Meaningful Comments
"Source code must document itself" is a common motto among clean coding advocates. However, it is not always possible to provide meaning to the user using only well-written source code. Sometimes, it is necessary to give an additional explanation about obscure passages or specific logic.

Comments must be written according to a previously agreed format, therefore the user can find the needed information fast. Also, comments must be short and condense as much information as possible, avoiding long and hard to read chunks of text.

### 5. Test the Code
Testing is ordinarily used as a measure to ensure that some implementation is compliant with its requirements. It is also responsible for keeping the code clean, flexible and maintainable, therefore changes can be introduced without breaking anything. Finally testing provides important insights to the developer, therefore helping to create well-written code.

It is important to choose a proper test suite that is recommended for the framework in use, following its philosophies and conventions. Also, tests must be readable, dense and assertive. Each test must deal with one feature at a time and run autonomously. Variables and memory allocated before each test need to be released after each one completes.

## Conclusion

Nowadays, the pace of technological change is growing faster. Each day, developers are fixing broken code and adding new features to their respective projects. But, to each new feature or fix, many other errors can be introduced and harm the software quality. To avoid this situation, improve the code quality and pay the existing technical debts are fundamental. To make this feasible, the use of clean coding techniques is fundamental.

Clean coding procedures are concise, simple. They emphasize that the programmer truly owns the code he produces and that he is the main responsible for the quality of the final product. Therefore, for those measures to be effective, the development team has to be sure that everybody is aware of this commitment and enforce it.

For more content related to clean coding, I recommend the book Clean Code: A Handbook of Agile Software Craftsmanship by Robert C. Martin. 

If you already read the book but want just a summary to make a checklist, [this gist is for you](https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29).