DEV Community

Caique Santos
Caique Santos

Posted on

How to write a Clean Code

Introduction

Clean Code is a concept popularized by the book of the same name, written by Robert C. Martin. The main ideia of the book is that a clean code can be read and enhanced by a developer other than its original author. The pillars of this concept are the following below:

Clear naming:

Instead of using:
var x = GetData();
Prefer:
var userEmails = GetUserEmails();

Functions responsability

A function should be as short as possible, and do only one thing.
Avoid:
ProcessUserDataAndSendEmai(user);
Instead, prefer:
ProcessUserData(user);
SendEmail(user);

Low coupling

Avoid tight coupling by instantiating dependencies directly:
private EmailService _emailService = new EmailService();
Prefer depending on abstractions:
private IEmailService _emailService;

Self-explanatory code

Comments can be helpful, but code should be clear on its own.
Avoid:
// increase processed items count
count++;

Prefer:
processedItemsCount++;

Consistency

You should stick to a standard. Avoid mixing different naming conventions:
var itensCount= 5;
var discount_amount= 0.2;

Use the same pattern:
var itensCount= 5;
var discountAmount= 0.2;

Overview

Good code is code that anyone can understand quickly.
You should be able to come back to it years later and still understand it.
It should also be easy to change.

Top comments (0)