+25 Tips For Writing Clean Code

Sonia Valdez
9 min readJul 30, 2023

--

One of the essential skills for developers is writing clean code. Clean code is easy to read, understand, and maintain. It adheres to a set of conventions, standards, and practices that make it simple, concise, and expressive. Clean code avoids complexity, redundancy, and other code smells and anti-patterns that can hamper the quality and performance of the code.

Why should we write clean code?

Clean code is a valuable practice for developers and their projects. It offers several advantages, such as:

Better communication

Clean code expresses the logic and purpose of the code clearly and concisely. This makes it easier for other developers to understand and modify the code in the future. It also helps you recall your own decisions and reasoning when you revisit your own code after a while.

Fewer errors

Clean code avoids unnecessary complexity, confusion, and ambiguity that can lead to bugs and mistakes. It also facilitates debugging and testing by making the code more predictable and consistent.

Higher productivity

Clean code saves time and energy in the long term. It allows you to reuse your code, refactor your code, and extend your code with less difficulty and more confidence.

More satisfaction

Clean code makes you proud of your work and gives you a sense of achievement. It also makes your code more enjoyable and fun to work with.

The Tips!

Before reading, I should say that I am using PHP examples in this article, but these tips are for any programming language.

Follow these tips and best practices that cover various aspects of programming:

1. Pick the best solution.

Consider the advantages and disadvantages of different options, such as programming languages, frameworks, libraries, or tools, and select the one that meets your needs and goals most effectively. Don’t follow the crowd or the hype without thinking critically.

2. Make your code more concise and clear.

Only keep what is essential for your code to work and convey its purpose.
Delete any comments, whitespaces, variables, functions, etc. that are redundant or irrelevant.

For example, instead of writing:

<?php
$colors = array("red", "green", "blue");
?>

You can write:

<?php
$colors = ["red", "green", "blue"];
?>

3. Writing code that is easy to understand and maintain.

One way to achieve this is to use self-explanatory code, which means choosing names for your code elements that clearly describe their purpose and functionality. Avoid using short or obscure terms that may be unfamiliar or ambiguous to others who read your code.
Make your code easy to understand and predictable. Your code should do what its name, purpose, and context suggest, without causing any confusion or unwanted outcomes. Keep your code free of surprises or hidden effects.

For example, instead of writing:

<?php
$r = $_GET["r"];
if (is_numeric($r) && c($r)) {
echo "The radius is " . $r;
}
?>

You can write:

<?php
$radius = $_GET["radius"];
if (is_numeric($radius) && checkNum($radius)) {
echo "The radius is " . $radius;
}
?>

4. Adhere to conventions.

Make your code consistent and conform to the standards of your programming language. Use proper indentation, spacing, capitalization, punctuation, etc. to enhance the readability and structure of your code.

<?php
// Declare the namespace according to PSR-4
namespace App\Models;

// According to PSR-12,
// The opening brace for the class MUST go on its own line.
class User
{
// Properties and Methods
}
?>

5. Writing functions short and simple.

Each function should have a clear purpose and perform only one task. Ideally, a function should not exceed 20 lines of code or have more than 3 parameters. This makes the code easier to read, test, and reuse.

<?php
function circle_area($radius) {
$area = 3.14 * $radius * $radius;

return $area;
}
?>

6. Writing good comments.

Comments are useful tools to clarify your code, but they should not be overused or misused. Only comment on things that are not self-explanatory or obvious from the code itself. Instead of telling what your code does, focus on explaining why it does it. This way, you can make your code more readable and maintainable.
Use clear and concise text to explain what your code does and how it works.

<?php
// Define a function that takes a radius as a parameter
// and returns the area of a circle
function circle_area($radius) {
// Calculate the area using the formula: area = pi * radius * radius
$area = 3.14 * $radius * $radius;

return $area;
}
?>

7. Use a consistent naming convention.

Choose a style that suits your language and project, and stick to it. Avoid using different names or formats for the same variable, function, class, or other element.

<?php
// I am using camelCase naming convention for variables.
$firstName = "John";
$lastName = "Doe";
?>

8. Re-usability, Organize code into modules or classes.

This will make your code easier to reuse and maintain, as you can avoid repeating the same code in different places.
Encapsulation is a technique that helps you achieve this by hiding the internal details of your code, exposing only the relevant behavior or interface, and abstracting your code by simplifying it and reducing its dependency on other parts of the code.
This technique that breaks down a large and complex system into smaller and simpler units. These units have high cohesion, meaning they group together related functionality, and low coupling, meaning they can be reused and maintained independently.

<?php
namespace App\Models;

class User {
// Properties
public $id;
public $name;
public $email;

// Methods
function __construct($id, $name, $email) {
// Constructor to initialize the object
$this->id = $id;
$this->name = $name;
$this->email = $email;
}

function get_id() {
// Getter method to return the id
return $this->id;
}

function get_name() {
// Getter method to return the name
return $this->name;
}

function get_email() {
// Getter method to return the email
return $this->email;
}

function set_name($name) {
// Setter method to change the name
$this->name = $name;
}

function set_email($email) {
// Setter method to change the email
$this->email = $email;
}
}
?>

9. Limit the number of parameters.

You can use default values, optional parameters, or objects to pass multiple arguments to a function.

For example, instead of writing:

<?php
function add_numbers($a, $b, $c, $d) {
return $a + $b + $c + $d;
}
?>

You can write:

<?php
function add_numbers($numbers) {
return $numbers;
}
?>

10. Limit the number of characters in line.

You can use line breaks, parentheses, or operators to split long expressions into multiple lines.

For example, instead of writing:

<?php
echo "This is a very long sentence that might exceed the recommended number of characters in a line and make the code less readable.";
?>

You can write:

<?php
echo "This is a very long sentence that might ",
"exceed the recommended number of characters ",
"in a line and make the code less readable.";
?>

11. Define meaningful constants.

Instead of using arbitrary numbers or strings in your code, define and use constants that convey their meaning or purpose. This way, you can avoid hard-coding values that may change or be unclear to others.

<?php
define("PI", 3.14);
?>

12. Explanation of the exception.

When your code runs into an error or an exception, make sure to provide descriptive and helpful messages. These messages should explain what went wrong, where it happened, and how to fix it. This way, you can debug your code more easily and avoid frustrating your users.

<?php
function checkNum($number) {
if($number > 1) {
throw new Exception("Value must be 1 or below");
}
return true;
}
?>

13. Writing clear and concise commit messages.

Follow a consistent format that includes a summary of what you changed, why you changed it, and how it affects the codebase.

14. Make sure you test your code frequently and thoroughly.

You can use different kinds of tests, such as unit tests, integration tests, end-to-end tests, etc., to check if your code meets the requirements and to detect any errors before they cause problems.

15. Automate and optimize your tasks.

You can use linters to detect and fix syntax errors, formatters to align your code with consistent standards, debuggers to identify and resolve bugs, and so on.

16. Achieving optimal results with simplicity.

Create a solution that is optimal in terms of performance and resource usage, while keeping it simple and readable.

17. Avoiding unnecessary verbosity and obscure brevity.

Clean code should be concise and clear, but not at the expense of each other. Avoid writing code that is too short to understand or too long to read.

18. Clear flow of execution.

This means that your code should follow a logical order of steps from the beginning to the end, without any unnecessary or confusing jumps or branches.

19. Single responsibility principle.

This is a design guideline for software development, it suggests that each function or class should have a clear and specific purpose, and only one reason to change. This way, the code becomes more modular, reusable, and easier to maintain. For example, a function that calculates the area of a circle should not also print the result or save it to a file. Instead, it should only return the value and let other functions handle the output or storage.

20. Single source of truth.

A piece of information or data should have only one authoritative source in your codebase. This principle helps you avoid inconsistencies and errors that can arise from having duplicate or conflicting versions of the same data or logic.

21. Folder structures.

This a way of grouping your code files into meaningful and logical categories. By using folder structures, you can separate different layers, components, or features of your codebase. This makes your code more organized, modular, and reusable.

22. Writing Documentation.

This is the process of creating written records that explain the purpose, logic, and usage of your code. It helps your target audience understand, maintain, and modify your code. Documentation should be clear, concise, and informative.

23. Wrapping up.

The final step of writing clean code is to wrap it up. This means checking your code for any errors, inconsistencies, or possible enhancements. You can refactor your code to make it more concise and elegant. You can also test your code to verify that it works as expected. Wrapping up your code will ensure that it is easy to read, understand, and maintain.

24. Don’t worry about optimization too soon.

Write code that is easy to read and understand first, then make it faster or more efficient if necessary. Clarity and correctness are more important than performance, unless you have a clear reason or benefit for sacrificing them.

25. Writing examples.

To show how your code behaves and what it does, you need to use examples that are meaningful and clear. Your examples should cover different cases and scenarios that your code might encounter. You should also use data and inputs that are realistic and relevant to the problem you are solving with your code.

26. Enhance your skills.

As a developer, you should always strive to learn new things and enhance your skills. There are many resources that can help you write clean code and follow best practices, such as books, articles, blogs, etc. You can also learn from other developers by reading their code and listening to their feedback. Don’t be afraid to experiment with different tools, techniques, and approaches to writing clean code. You might discover something that works better for you or your project.

Conclusion

Writing clean code is more than just a technical skill. It is also a mindset and a habit that shows respect for yourself, your colleagues, and your customers. It is a way of writing code that simplifies your life, enhances your projects, and increases your satisfaction.

To write clean code, you need to practice regularly, follow some discipline, and seek feedback from others. You also need to adhere to some principles, guidelines, and best practices that have been established by many successful developers over the years.

--

--

Sonia Valdez
Sonia Valdez

Written by Sonia Valdez

Tech lover, coder, blogger. CS grad, software dev. Curious, creative, passionate. I use technology to make a positive impact on the world.