How to Write Beautiful Code in Any Language

How to write beautiful code in any programming language

Share This Post

Coding is like poetry, it can be beautiful and fulfilling. And, like with poetry, you simply cannot clash a few words together and make a poem. Instead, you need to carefully select each word and feel how they work together. Code is exactly the same. In other words, you need to have some skills to write beautiful code. However, you don’t need a Ph.D. at all, you only need to get a few things right. In this post, we will see just that, and we will learn how to write beautiful code, in any language.

Why Write Beautiful Code?

Everything happens for a reason, and before you embrace the beautiful code cause, you may want to understand why. Well, in short, it will make you more productive and more professional. You will enjoy it, and your coworkers will do just that.

Here is a quick recap of the benefits of writing beautiful code.

  • Code is clear to read
  • You can quickly understand your code, even after years
  • The code is easy to share because others can clearly understand it
  • Making changes is quicker, and you reduce the risk of breaking something
  • It enables to write in-code documentation
  • You can avoid bugs as you completely understand how everything works

All of that makes you a rockstar developer. This is good for you, awesome on open-source projects, and great if you want to land a job.

And what are the downsides of writing beautiful code? You can imagine by now, there is none! However, it is worth mentioning that writing beautiful code will take a little more time than writing bad code. In spite of this, making changed to bad code can take a lot of time and break everything. Thus, in the long run, you actually save time by writing beautiful code. There is no catch!

How to Write Beautiful Code?

If your code is really messy, you may want to fix it first. To do it, we have a great guide on how to avoid spaghetti code. Once your code is back in decent shape, you can work on making it sharper. This is what this post is all about.

Instead, if you are starting from scratch, you may as well start here. We have some easy steps you can follow to write beautiful code.

  1. Set up a git repository
  2. Prepare a .gitignore file from the beginning
  3. Define how to use git
  4. Define how to Write Beautiful Code
  5. Write docstrings
  6. Refactor the code often

Set up a git repository

You really cannot skip this step. If you want to write beautiful code, you must use git for version control.

GitHub is a free cloud repository to help you write beautiful code
The GitHub logo.

Remember, the beauty of code comes from its simplicity and clarity. And it may surprise, but you always start with the most beautiful code ever. Yes, an empty file – it couldn’t be neater. Making changes can sometimes make your code a little bit more ugly, particularly if you change things fast. With git, you can get back to any point in time of your code.

You can use git for free, forever. There are many options out there. I am personally very happy with Azure DevOps, but the most popular way to go is GitHub. If you haven’t already, log in to GitHub and create your account. Once you do that, you can create a private repository, which is like a cloud folder to hold your code. To sync to your computer, you need to use a git client. You can use the official git, but I prefer the GitHub Desktop client, which has a wonderful GUI.

At this point, you are all set to start creating some files in your project. But don’t start to write your code just yet. We need to do some more things!

Prepare a .gitignore file from the beginning

There are things you want to include in your version control and things that you don’t. For example, your IDE may add some settings or cache folders to your project, but you don’t really want to keep track of those.

To be honest, tracking them would be even harmful. In fact, if they are part of the code, any developer working on it would get them. Imagine how painful would be to have all the graphical settings of your IDE changed without you knowing. Yup, this happens often enough if you are not sure about what to include in your versioning.

The .gitignore file helps you solve this problem. It is simply a file where you tell which other files git should ignore. You can write one file per line, and also refer to entire folders. At a minimum, you need to have one of those files in your project root. If you want to go overkill, you can have more of them, one in each folder, to customize the settings of each folder.

You don’t need to be a genius to write a .gitignore file. In fact, you can find only pre-made versions that will suit your needs. Just look for the .gitignore of your programming language, as they may differ quite much. Here we have some great examples.

Of course, you can customize that file as much as you please.

Define how to use git

This may be natural if you’re familiar with git, but if you are a newcomer you may be confused instead. In any case, it is worth spending some words on this.

Git has a wonderful concept of branches to represent how your code evolves over time. Think of your code as a growing tree. It starts as a single stem, but then a branch forks away from the central body. In this branch, your code changes somehow. Some files appear, others vanish, and others are changed. Now, the analogy with the tree falls apart. When the branch is “ready”, it merges back into the main body.

This allows you to make changes to your code in a protected environment. Even better, within a branch, you submit changes gradually by committing a file only when you feel it should appear in the branch. If something goes bad, you can rever to a previous commit, or even ditch an entire branch.

Furthermore, this allows multiple developers to work on the same project at the same time, each working on separate features. You simply have each developer on its own branch.

Defining how to use git means deciding how to create and merge branches.

There are lots of ways of using git, but we will give you a simple one that works for most projects.

You need to have one main branch, the master, that represents the code as it is on your production server or release. From that, work a dev branch for development. This is where you patch things together before pushing it into the master. Then, for each feature you want to deploy, you create a new branch from the dev one. If the features are big, you can even create sub-branches.

Define how to Write Beautiful Code

The file is the file any developer approaching your project should read. It will be the reference even for you that created the project! Thus, it is the best place to be clear about how to write code. Here, you should define how to write beautiful code.

In fact, the best way to write beautiful code is to be consistent, using always the same style. So, you need to be clear about such style at the beginning. Answer questions about the style below.

  • How do we write the names of variables? camelCase, PascalCase, or snake_case? What_About_A_Combination?
  • What is the minimum level of documentation we should put in docstrings?
  • Do we indent with tabs or with spaces? How many tabs or spaces we use for an indent level? (Prefer spaces over tab)
  • After a condition, do we directly open a curly bracket or do we open it on a new line? (This applies only to C-like languages)
  • Do we need to follow some naming convention? (more on that later)

You may even add additional questions you want to answer. The best way to write beautiful code is to take your time on this step. Do your search about your language, see other projects you can quickly understand, and decide how what beautiful code is for you.

Just like in poetry, there is no predefined rule on what is a beautiful piece of code. Of course, we have some guidelines, but in the end, it is more like an art. Any skilled developer can quickly see if a code is beautiful or not just by opening a file.

Write docstrings

Docstrings are pieces of documentation you put inside your code. They define what a function does, what are its parameters, and what are its returns. They can also document a class, a module or even just a file. However, documenting functions and class members is really a requirement to write beautiful code.

Below, an example of C-like docstring that can work for PHP as well as Java.

 * Create a signed version of the XML file
 * @param string $file_name    Name of the file to sing
 * @param string $cert_file    Certificate to use for the signature
 * @param string $cert_pass    Password to open the certificate
 * @param string $dest_file    Name of the output file
 * @return bool                True if the operation was succesful
function sign_xml(string $file_name, string $cert_file, string $cert_pass, string $cert_pass) : bool
   // Some code

As a rule to write beautiful code, write docstrings for all members and functions of all classes of your project.

Docstrings are a wonderful way to document your code because they are inside the code. This means they automatically follow the same versioning, and you don’t forget to update them when you change your code because they are in the same place.

Refactor the Code Often

This comes particularly easy if you work with a team, but it is something you can also do all alone. Refactoring the code means rewriting part of it. Not from scratch, of course. It means improving the quality of the code.

You select a piece of code you want to refactor. This might be a file or even just a function. You spend some time looking at it, with two major goals.

  • Increase its performance (reduce the usage of CPU and memory)
  • Reduce the amount of code

With only these two goals in mind, you can be awesome at refactoring. Ideally, you should refactor the code written by someone else. Instead, if you are working alone, refactor your code only after some time you have first written it. Only in this way, your mind will be fresh and open to optimizations.

This is probably the most important concept you want to remember about how to write beautiful code, in any language.

About Naming Conventions

Ah, naming conventions. From those you can quickly tell if a developer is a newbie, or instead if it is a pro. Chose your naming conventions carefully. In short, a naming convention is a way you agree to call things. It typically refers to variables, classes, methods and so on.

The golden rule here is to go with abstraction and do not include any reference to the code itself. With that, I mean that having a variable that contains “variable” in its name is something pretty dumb to do. Of course, a variable is a variable, what is the point of writing it in its name? What is the added value? None!

Also, try to avoid using the variable type in the name of the variable. So, having string or boolean in the name is not the way to go.

Use longer names for more important variables that you use often, and try to reduce the scope. This means that in any place of your code, the accessible variables should be only a few. Yes, global variables are a bad thing.

In Summary

In this short post, we got you on the right track to write beautiful code. If you just have to get one thing out of this post, get code refactoring. It will change the way you code. It will change your career!

Go and write beautiful code! If you have some suggestions you thin we should add in this guide, just let me know in the comments.

Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded with the same principle: I share what I learn so that you get value from it faster than I did.
Picture of Alessandro Maggio

Alessandro Maggio

Project manager, critical-thinker, passionate about networking & coding. I believe that time is the most precious resource we have, and that technology can help us not to waste it. I founded with the same principle: I share what I learn so that you get value from it faster than I did.

Alessandro Maggio