How to Write Clean Code?

readTime

7 min

How to Write Clean Code?

Want to write clean code? Then this article is just for you.

Clean code is a key factor, and the ability to create it distinguishes a good programmer from one who is just trying to be one.

In this post, you’ll learn how to create readable, clear, and understandable code that will not only make your work easier but also make other developers want to work with you.

What is Clean Code?

Before we begin, it’s worth asking: What exactly is clean code?

Clean code is code that is easy to read, understand, and maintain.

Such code is written clearly, using good programming practices, making it less prone to errors and easier to develop and maintain over time.

Clean code is not just functioning code; it’s code that is readable for other developers.

This means that someone else (or yourself after a few months) can easily understand what your code does and why it was written in a certain way.

This doesn’t mean your code will always be perfect.

Often, this will depend on limited time or your skills. My code often isn't perfect, especially the code I wrote at the beginning of my career.

The goal is to strive for perfection and always keep these principles in mind. Because even if your code won’t be flawless, it will at least get closer to that state.

Why Should You Write Clean Code?

You might wonder why it’s worth spending extra time writing clean code.

Here are a few reasons:

  • Easier maintenance: Clean code is simpler to modify and debug.
  • Team collaboration: Other developers will understand your code more easily, speeding up team projects.
  • Fewer errors: Clear code reduces the risk of introducing errors when making changes.
  • Scalability: Clean code is easier to expand in the future.
  • Professionalism: Writing clean code shows you are a professional who cares about the quality of your work.

Good Programming Practices

Let’s move on to specific good practices that will help you write clean code.

Naming Variables and Functions

Naming is the foundation of code readability.

Good names for variables, functions, and classes should be descriptive and understandable.

Bad code example:

java
int a = 5;
int b = 10;
int c = a + b;

Good code example:

java
int numberOfApples = 5;
int numberOfPeaches = 10;
int totalFruitNumber = numberOfApples + numberOfPeaches;

Thanks to descriptive names, you immediately know what each variable represents.

Best Practices in Naming:

  • Consistency: Use a consistent naming style throughout the project.
  • Avoid abbreviations: Unless they are widely recognized.
  • Language: Choose one language (English is strongly recommended) and stick to it throughout the code.
  • Capitalization: Use camelCase or snake_case conventions, but be consistent.

DRY Principle (Don’t Repeat Yourself)

The DRY principle states to avoid repeating the same code in different places.

Duplicating code increases the risk of errors and makes maintenance harder.

Bad code example:

java
public void sendWelcomeEmail(String email) {
    // Code to send email
}

public void sendReminderEmail(String email) {
    // The same code to send email
}

Good code example:

java
public void sendEmail(String email, String subject, String content) {
    // Code to send email
}

This way, we create a single function that handles different cases.

KISS Principle (Keep It Simple, Stupid)

The KISS principle encourages keeping code as simple as possible.

Avoid unnecessary complexity that may hinder understanding the code.

Bad code example:

java
if (status == true) {
    if (user.isActive()) {
        if (!user.isBlocked()) {
            // Execute operation
        }
    }
}

Good code example:

java
if (status && user.isActive() && !user.isBlocked()) {
    // Execute operation
}

Simpler code is easier to read and maintain.

YAGNI Principle (You Aren’t Gonna Need It)

Don’t create functionality that you don’t currently need.

Adding unused code increases complexity and may introduce additional errors.

Example:

If your application currently only supports Polish, don’t implement a multilingual mechanism unless necessary.

Formatting and Consistency

Formatting code greatly affects readability. Use appropriate indentation, spacing, and line breaks.

Bad code example:

java
public class Example{
public void method(){
System.out.println("Unformatted code");}}

Good code example:

java
public class Example {
    public void method() {
        System.out.println("Formatted code");
    }
}

Formatting Tips:

  • Use indentation: Usually 4 spaces or a tab.
  • Spacing: Apply spaces around operators.
  • Lines: Avoid overly long lines of code; aim for 80-120 characters max.

Commenting Code

Comments are important, but the code should be readable enough that comments aren’t often needed.

Bad code example:

java
// Increment the counter
i = i + 1;

Good code example:

java
counter++;

Good naming and readable code reduce the need for excessive comments.

Avoiding "Code Smells"

Code smells are early signs of potential issues.

These can include:

  • Code duplication
  • Overly long methods
  • Too many parameters
  • Excessive complexity

Example:

If you have a function with 10 parameters, it’s worth splitting it into smaller, more readable parts.

Code Refactoring

Refactoring is the process of improving code without changing its functionality.

Regular refactoring helps maintain code cleanliness and improves readability.

Example before refactoring:

java
public void processData(String data) {
    // Code processing data
    // Code validating data
    // Code saving data
}

Example after refactoring:

java
public void processData(String data) {
    String processedData = process(data);
    if (isValidData(processedData)) {
        saveData(processedData);
    }
}

private String process(String data) {
    // Code processing data
}

private boolean isValidData(String data) {
    // Code validating data
}

private void saveData(String data) {
    // Code saving data
}

Now, each function has a single responsibility, enhancing code readability.

Practical Tips for Beginner Programmers

Learn from Experienced Programmers

If you’re a beginner, take advantage of the experience around you.

Read their code, participate in code reviews, ask questions, and do more than you need to.

Write Unit Tests

Unit tests help maintain code quality and ensure that changes don’t introduce errors.

Example unit test in Python:

python
import unittest

class TestCalculator(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)

if __name__ == '__main__':
    unittest.main()

Avoid Hardcoding Values

Don’t hardcode constant values directly into the code. Use constants or configuration files.

Bad code example:

java
public void setLimit() {
    int limit = 100; // Hardcoded value
    // Code using limit
}

Good code example:

java
private static final int USER_LIMIT = 100;

public void setLimit() {
    // Code using USER_LIMIT
}

SOLID Principles

Now, let’s quickly go over the SOLID principles, which are fundamental to writing clean code.

S - Single Responsibility Principle

A class or function should have only one responsibility.

Example:

A User class should manage user data, not, for example, handle database connections.

O - Open/Closed Principle

Code should be open for extensions but closed for modifications.

Example:

Instead of modifying an existing class, create a subclass and add new functionalities.

L - Liskov Substitution Principle

Derived class objects should be replaceable with objects of the base class.

I - Interface Segregation Principle

It’s better to have multiple specific interfaces than one general one.

D - Dependency Inversion Principle

High-level modules should not depend on low-level modules.

Summary

Remember, you write code for people, not for machines. Writing clean code is not only a sign of professionalism but also an investment in the project’s future.

Clean code improves software quality, simplifies reading, refactoring, and maintenance.

Remember:

  • Good naming of variables and functions.
  • Applying principles like DRY, KISS, YAGNI.
  • Regular refactoring and maintaining a consistent style.
  • Avoiding code smells and excessive complexity.
  • Constant learning and improving your skills.

Start writing clean and understandable code today 😉

authorImg

Witek Pruchnicki

I passionately share knowledge about programming and more in various ways.