Sitemap
Om Parkash Sarangani

Om Parkash Sarangani

A software engineer who loves to solve complex software problems through design and code.

Clean Code Fundamentals: 07 Lessons to Write Clean & Better Code

5 min readMay 14, 2023

As developers, we all want to write clean and maintainable code. But what exactly is clean code, and how can we achieve it? The answer can be found in the book Clean Code Fundamentals.

In this article, we’ll cover 07 key lessons from the book that can help you write better code.

Press enter or click to view image in full size

Lesson 1: Meaningful Names

Choosing good names for variables, methods, and classes is crucial for writing clean and maintainable code. Names should be clear, concise, and convey the purpose of the code they represent. Take a look at this example:

// Bad example
int d; // elapsed time in days

// Good example
int elapsedTimeInDays;

In the bad example, the variable name “d” is not descriptive enough and can cause confusion. In the good example, the name “elapsedTimeInDays” is much clearer and leaves no room for misunderstanding.

Lesson 2: Functions Should Do One Thing (Single Responsibility Principle)

Functions should have a single responsibility and do one thing only. If a function is doing multiple things, it can become hard to understand and maintain. Here’s an example:

// Bad example
public void saveAndSendEmail(User user) {
saveUser(user);
sendEmail(user);
}

// Good example
public void saveUser(User user) {
save(user);
}
public void sendEmail(User user) {
send(user);
}

In the bad example, the function “saveAndSendEmail” is doing two things at once — saving the user and sending an email. In the good example, we have two separate functions — “saveUser” and “sendEmail” — each with a single responsibility.

Lesson 3: Comments Shouldn’t Be Used to Explain Bad Code

Comments are important for explaining why code is written a certain way, but they should not be used to explain bad code. Instead, strive to write code that is self-explanatory and easy to understand. Here’s an example:

// Bad example
// If x is less than or equal to 0, set y to 1
if (x <= 0) {
y = 1; // Set y to 1
}

// Good example
if (x <= 0) {
y = 1;
}

Lesson 4: Avoid Magic Numbers

Magic numbers are hard-coded values that appear in code without explanation. They can be confusing and make code difficult to read and maintain. Instead, use named constants or variables to give these values context. Here’s an example:

// Bad example
public double calculateCircleArea(double radius) {
return 3.14 * radius * radius;
}

// Good example
public static final double PI = 3.14;

public double calculateCircleArea(double radius) {
return PI * radius * radius;
}

In the bad example, the value "3.14" is a magic number with no context. In the good example, we've defined a constant "PI" with a clear value, making the code easier to read and understand.

Lesson 5: Don’t Repeat Yourself (DRY)

Repeating code is a bad practice as it leads to maintenance issues and makes the code harder to read and understand. It is best to extract common code into separate functions or classes to avoid repetition.


// Bad example
double areaOfRectangle(double height, double width) {
return height * width;
}

double perimeterOfRectangle(double height, double width) {
return 2 * (height + width);
}


// Good example
double areaOfRectangle(double height, double width) {
return height * width;
}

Lesson 6: Write Short and Concise Functions

Functions should be short and concise, and they should do one thing only. This makes the code more readable and easier to understand. The function should have a clear and descriptive name that conveys the purpose of the function.

Get Om Parkash Sarangani’s stories in your inbox

Join Medium for free to get updates from this writer.

Bad Example:

// Bad example

void validateUser(User user) {
if (user.getFirstName() == null || user.getLastName() == null || user.getEmail() == null) {
throw new IllegalArgumentException("User details missing");
}
if (user.getPassword().length() < 6) {
throw new IllegalArgumentException("Password must be at least 6 characters long");
}
}

// Good example

void validateUser(User user) {
validateUserDetails(user);
validatePassword(user.getPassword());
}
void validateUserDetails(User user) {
if (user.getFirstName() == null || user.getLastName() == null || user.getEmail() == null) {
throw new IllegalArgumentException("User details missing");
}
}
void validatePassword(String password) {
if (password.length() < 6) {
throw new IllegalArgumentException("Password must be at least 6 characters long");
}
}

In the above example, we have split the validateUser() function into two smaller functions, validateUserDetails() and validatePassword(). This makes the code more modular and easier to understand.

Lesson 07: Keep It Simple

The last and most important principle of clean code is to keep it simple. The code should be easy to read and understand. It should not be complicated or convoluted. Avoid unnecessary complexity, duplication, and over-engineering. Simplicity is key to producing clean and maintainable code.

Here is an example of a complex piece of code:

public class ComplexCode {
public void doSomething(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k) {
int result = a * b + c / d - e + f * g - h / i * j % k;
System.out.println("Result: " + result);
}
}

This code is hard to read and understand. It is also difficult to modify and maintain. Instead, it would be better to break it down into smaller, simpler pieces of code:

public class SimpleCode {
public int multiply(int a, int b) {
return a * b;
}
public int divide(int a, int b) {
return a / b;
}
public int modulo(int a, int b) {
return a % b;
}
public int calculate(int a, int b, int c, int d, int e, int f, int g, int h, int i, int j, int k) {
int result = multiply(a, b) + divide(c, d) - e + multiply(f, g) - divide(h, i) * modulo(j, k);
System.out.println("Result: " + result);
return result;
}
}

This code is much simpler and easier to read and understand.

Conclusion

In conclusion, writing clean code is not just about making the code look pretty, but it’s also about making the code easier to read, understand, and maintain. Applying the principles discussed in Clean Code Fundamentals can help you write cleaner, more efficient code that is easier to work with and understand.

Remember that writing clean code is a continuous process, and it’s important to constantly evaluate and improve your code as you go. By focusing on good design, clear and concise code, and effective testing, you can create code that is easy to maintain and extend over time.

By following the best practices and techniques discussed in this article, you can become a better programmer and create code that is not only efficient and effective but also clean and easy to understand. So, keep learning and keep improving your coding skills to become a better developer.

--

--

Om Parkash Sarangani
Om Parkash Sarangani

Written by Om Parkash Sarangani

A software engineer who loves to solve complex software problems through design and code.