5 Tips for Writing Readable Code

Whether you are an absolute beginner just learning the basics of coding or a seasoned veteran working in huge, legacy codebases, you need to write readable code.


1. Consistently format your code

"Code Formatting" means organizing your code, line breaks and spacing in a consistent and meaningful way.

Formatting is extremely important because it makes code more readable to humans. And humans are the ones reading & writing code. You are one of those humans and taking the time to format your code properly will start saving you headaches immediately.

I have often noticed that the new programmers who neglect to format their code are the most likely to get stuck and encounter bugs they don't understand. When code is indented inconsistently, logic bugs are easy to miss.

I strongly recommend using an automatic formatter for your code. Most development environments already know how to format code and everyone should memorize that hotkey by heart.

Try it now: Configure your environment to "Format on save". Most IDEs can be configured to automatically format your code when you save a file. This is a great way to always keep your formatting consistent and spot errors sooner.

2. Make naming your first priority

If you give things great names, you will find that your code is much easier to work with. Naming is probably the most important and the most challenging skill in all of software development. A good name can capture deep meaning and a bad name can mislead readers.

Consider each of the following as you practice naming classes, variables and methods:
  1. One name per concept, one concept per name
    Each term you use should have a single, unique meaning. Avoid cases where important names are accidentally shared by different concepts. This makes it much easier to know at a glance what something represents and makes it easier to find with "Find All"/grep
  2. Be consistent in your naming schemes
    There are many common naming principles and different codebases have adopted different best practices. Always understand the best practices in your current codebase and be ruthlessly consistent.
  3. Verb methods
    Always start your method names with a single verb. A method does something. "add numbers", "fetch data", "sort list", etc. This is a well-established pattern and one you should always follow
  4. If you can't think of a concise, meaningful name, refactor
    If you need to name a method or variable but it does too many things to capture in a meaningful way, that's a big sign you need to refactor your code. This often happens when one method is doing too many different things. Think about how you can split a complex method up into smaller, well-named methods.
As you write more code and read more code, you'll start to notice good names and bad names. Pay attention and learn as you go. These concepts will help you become better at naming only through consistent practice and reading.

3. Keep similar things together

The closer together you keep related code, the easier it will be to follow. When you are writing functionality, think about how to split it up in a way that keeps the most-related parts close to each other in the code base. Think about how each part of the code will be used.

Don't be afraid to refactor your code as you go. If you find that your current structure isn't ideal, you should be able to move your code around. Refactoring your code is a big part of a software engineer's job and often one of the most rewarding.

4. Comment, but don't overdo it

Comments are useful ways to explain why your code does what it does. Comments are also very useful as "Documentation" for methods & parameters. But you really don't need to comments to explain what each line of code does.

If your preferred language has a standard format for documenting classes and methods, learn it! Most IDEs will show doc-comments in their code-help tooltips

See this JavaScript example using JSDoc comments in VSCode: 

As I type, VSCode will show me basic comments about my method and it's parameters (that I added). This is very useful when you're working in large code bases because you don't have to remember all the context. 

Try it now: Look up how to write doc comments in your preferred language and try using them on your next project.


5. Don't try to be clever

The most readable code is frequently the simplest code. On the other hand, the most bug-prone, hard-to-read code is usually very complex.

Aim to make each line simple. Try to avoid nested if-statements and loops. Don't worry about optimizing for performance (until you actually encounter a performance problem). 

There is a common principle in programming called "Don't repeat yourself" (DRY). The idea is that if you're writing the same code many times, it should be extracted into a common function. This is generally good practice, but don't go overboard. Some engineers are too eager to try to minimize repetition so much they write complex code. Aim to remove most repetition but always weigh the complexity of your approach before committing.

Along these lines, it can be very helpful to break up long statements into a series of smaller statements. Don't be afraid to define new, well-named variables to hold intermediate values. Having better linear flow can make debugging easier too.

Example: A long if statement (these are very common):
return typeof input === "string" 
  && matchesFirstName(input) && matchesLastName(input
  && address !== null && isNearby(addressLOCATION);

To improve the readability, you could break out some of the logic into variables:
Rewrite:
const doesNameMatch = typeof input === "string" && matchesFirstName(input) && matchesLastName(input);
const isAddressNearby = address !== null && isNearby(addressLOCATION);
return doesNameMatch && isAddressNearby;

This code is more self-documenting and easier to follow. If you're fixing a bug or changing functionality, you only need to pay attention to one line.

In Conclusion

Programs should first and foremost prioritize human readability. This article shared five key ways to write more readable code.

Programming is an art as well as a science. You will learn to write better code through extensive practice and reading other's code too. Supplement your practice with regular learning through blogs like this, find a mentor or get code reviews from someone you respect.


Comments