Blog articles

10 Tips for Writing Clean Code

Updated on October 20, 2022

Clean code is a reader-focused development style that produces software that's easy to write, read and maintain. Knowing how to produce clean code is an essential skill for software developers. Often, you may be tempted to consider your work complete when the application operates as expected. But we're not merely writing code for computer consumption.

Clean code is about recognizing that your audience isn't just a computer, it's real-live humans! With this principle in mind, let's review the reasons clean code matters and dive into some tips and tricks when it comes to how we can do it in practice.

What is clean code?

Clean code is clear, understandable, and maintainable. When you write clean code, you're keeping in mind the other people who may read and interpret your code at a later time. You're helping others understand the purpose of your code so that they can make changes to it eventually.

Clean code principles lead to source code that's highly modular and thus easier to read and test. If you think of these practices as part of a house, clean code is the foundation. Implementing clean code principles is a foundational skill that pays off especially well when it's time to refactor code or bring code under test. 

What are the 3 principles of clean code?

There are three core principles to remember when it comes to writing clean code:

  1. Choose the right tool for the job

  2. Optimize the signal-to-noise ratio

  3. Strive to write self-documenting code

10 steps to writing clean code

1. Follow conventions

Using a naming convention is a great way to get started — it keeps things clear and lets you know exactly what you’re working with. 

A naming convention basically means you decide you’ll call your variables by names that adhere to a certain set of rules. It can get hairy, and a lot of people don’t always agree on which is best. So to keep it simple. It can be something as simple as prefixing variable names with their data type, like this:

int iMyInteger = 10; 

float fMyFloat = 10.5f;
MyIntiger Code Snippet

2. Indicate variable scope

The next thing, which follows nicely from using naming conventions, is using a convention to indicate variable scope. Again, there are no rules, and everyone has their own way of doing it — as long as it’s consistent throughout all of your code, it will always be clear what can be used from where.

A common convention goes as follows:

//private and protected variables are prefixed with an underscore 
int _iWindowSize = 900;

//public variables are left as they would be normally
int iWindowSize = 900;

//constant values are in all caps and separated with underscores
int I_WINDOW_SIZE = 900;
360 no scope code snippet

3. Say what you mean

This is pretty straightforward, but it’s probably the most common and maybe the easiest one to forget. Easily the most frustrating thing for another developer looking at your code is seeing a variable with a misleading name or, worse, named with a single letter. 

Let’s take a look at an example of this:

int checkNum()
{
     if(n < max)
     {
          return -1;
     }else{
          return 1;
     }
}
variable with a misleading name

4. Whitespace is nice space

Using whitespace can be incredibly powerful and normally has absolutely no downside. Sometimes in languages like JavaScript where the file size of the source code itself is important, you might want your files to be small, and that whitespace can add a few extra kilobytes. When you can, keep all your whitespace during development so the code is readable. Then, use one of the many smart little programs that go through code and chop out all the whitespace just before you upload it.

5. Commenting saves lives — or at least headaches

Adding comments to your code can be invaluable—they can quickly show what a complex function is doing or explain the order of certain operations. Beyond explaining the purpose of the code itself, though, comments can help others understand what problems you were trying to solve with your code, which can help them come up with better solutions. Keep in mind that too much commenting can sometimes have a detrimental effect by creating messier code.

6. Automate to save time and space

Writing slightly more technical code doesn’t mean it has to be less readable. Multiple lines of duplicate code are not only harder to read, but they also increase the chance for error. The great thing about programming is that you can express complex commands in tidy, reusable, and clever ways.

Here’s an example of poor, duplicated code:

While this might look okay, and it is functional, it isn’t clear why any of it is happening at all. You can repair it with a simple comment that explains what this code does. 

box1.x = 10;
box1.y = 20;
box2.x = 30;
box2.y = 20;
box3.x = 50; 
box3.y = 20;
box4.x = 70;
box4.y = 20;
Duplicated Code Snippet

And here’s an approach that cleans everything up:

boxArray = [box1, box2, box3, box4];

for(int i = 0; i < sizeOf(boxArray); i++)
{
     boxArray[i].x = 10 + i * 20;
     boxArray[i].y = 20;
}
Clean code snippet for duplicated code example

7. Remember the power of i

When you have a code block with multiple loops one after the other, you need different iterator variables. There is always debate about what to use, and the answer is slightly subjective, but when they’re one after another, it makes sense to declare your iterator outside of the loop and reuse it. It’s not only better to look at, as it’s always clear that “i” is your iterator variable, but it’s also slightly more efficient.

Let’s look at an example of what I’m talking about:

//declare variable initially
int i ;

for(i = 0; i<10; i++)
{
     //loop stuff
}

for(i = 0; i<200; i++)
{
     //more loop stuff
}
declare your iterator outside of the loop and reuse it

8. Birds of a feather group similar variables together

When your projects start to get larger, your classes will likely have many variables. First, you should be keeping all of your variable declarations at the top of the page, or at the very least all together somewhere—this speeds up any kind of searching.

Second, even though they are all together, it often helps to arrange them in such a way that makes them even easier to comprehend. For example, grouping them all by what they are is a good way to go. It’s quite likely that you’ll have several types of the same object, so keep those all together in groups, and then maybe have a section for the miscellaneous ones underneath.

9. Keep it functional

Mile-long function definitions are an easy way to clutter your code. Normally it’s best to take a look at what’s actually being done. If a function is doing more than its name suggests, then perhaps some of the excess functionality could be split out into its own function.

10. Keep it classy

Similar to the functional problem, if there’s a large amount of functionality you’re keeping all in one place, it could be better to create a separate class to handle that functionality.

When it comes to writing, reading and maintainability, clean code is essential. The steps outlined above are not concrete rules. Use them as outline, or use them as a guide to find your own style and way of doing things. The important thing is this: Keep it tidy, clearly sectioned, and consistent. Anyone working with your code will appreciate the effort, and might even learn something from your example.

Interested in more clean code tips? You can try these courses from Pluralsight: Java Coding PracticesJavaScript Best PracticesC# Development Practices