11 Tips To Write Better Code

Get some tips on how to write better code.

Once you have the basics of a coding language under your belt or maybe even a few technologies, they’ll come a time when you think “I want to write better code”. Imagine that you’re able to solve problems easily, know the difference between a for loop and a while loop and have mastered functions. The next logical step is to start looking at what you’ve written and make it better. Here are 11 tips to help you start improving the quality of your code.

Use a style guide

You might, like I used to, think that style guides are just for how to present UI components - rules to create CSS or colour schemes etc. However, style guides do exist for your coding style too. Where I work, we use the JavaScript style guide from AirBnB. So what exactly is a programming style guide? It’s basically just a set of rules or best practices that you should follow to make sure everyone’s code in your organisation looks the same. It might cover things like, what variable types to use, when to use certain programming features.

Use a linter

A linter is a program that checks your code to see if it is breaking any pre-defined rules to make sure it is in line with your some pre-set guidelines. They can usually be integrated into your text editor too. This is great because your editor automatically yells at you when you’ve missed some whitespace or used a feature which has been discouraged with the pre-set rules. Linters are also especially powerful when you combine them with the rules from a style guide (see above). Why? Because everyone you are working with will be working to the same standard style guide and their linter will be telling them when there is an issue. Keeping everyone’s code consistent is a powerful way of improving your own coding style because it’s easy to check if you’ve deviated from the standard. Check your text editor’s plugin repository for linters.

Comments

So i’m assuming you know what comments are in your code and that by adding them you’re making your code easier to read for other developers. You might not think that adding comments is helping you to write better code. But adding some helpful explanations about what a particular function or loop is doing can help you to think about if there is a better way to do it. On the flip-side, if you’re feeling it necessary to pepper your code with comments because you think it will be confusing for others to look at then you need to rethink your approach to that particular problem.

Doc blocks

Following on from using comments, you should use doc blocks to annotate your functions / methods. So what is a doc block? It’s a big comment block above a function that describes what it does.

/**
 * This function takes exactly two parameters,
 * adds them togther then returns the result.
 * 
 * @param {number} a 
 * @param {number} b
 * @return {number} 
 */
function sumNumbers(a, b){
    return a + b;
}

The above is an example of a doc block for a JavaScript function. It’s pretty trivial but you can see how it makes it clear what the inputs and outputs of the function are. There are also some extra bits of information you can supply such as the types of parameters the function takes and also the return type, whether it throws an errors etc. Doc blocks are intended to be used by text editors and some documenting tools to provide information to users. But a well written doc block can also prevent you from having to put (too many) comments in your functions.

Variable naming

You may have at some point heard someone tell you to give your variables meaningful names. And it makes sense. See the example below - which is clearer?

var tc = 34;
var totalComments = 34;

It’s something we all forget from time to time. Sure, I know that tc referred to ‘total comments’ when I wrote the code but to other developers (including myself 6 months from now) it might not be that clear. In fact, i’ve been caught out on these quite recently and confused another developer when I sent the code to a pull request.

Look for better ways to write something (refactor)

Once you’ve got a function or part of your program working, it’s worth considering refactoring it to make it clearer and simpler. Refactoring is just the process of rewriting some or all of your code to make it easier to read and understand whilst keeping the same functionality. Take for example the following JavaScript function that removes unwanted elements from an array:

var array = [12,34,5,66,8,43,61,2]
var filteredArray = [];
for(var i = 0; i < array.length; i++) { if(array[i] >= 10){
    filteredArray.push(array[i]);
  }
}
console.log(filteredArray);

This works fine and it’s pretty obvious what’s going on. But the same functionality could be achieved with:

var array = [12,34,5,66,8,43,61,2]
console.log(array.filter(number => number >= 10));

Refactoring doesn’t necessarily mean rewriting everything to use the least amount of code possible. It just means finding better ways of doing things. And as such it can be done at any point in your project’s lifetime. So as you learn new things, you can go back and improve old code.

Remove bits that don’t need to be there

It might sound a bit obvious but if you have code in your project that’s not doing anything - remove it! It’s all too easy to forget about that function you wrote or that library you imported that’s no longer being used. If you leave stuff like this lying around it’ll confuse you, make other developer’s question why it is there and generally clutter up your project. Get rid.

Get others to review your code

Probably the single best thing to do in order to improve the quality of your code is to get someone else to look at it. If they’re more experienced than you then they’ll be able to impart their knowledge on how to do things in a better way or suggest improvements to your style. If they’re less or similarly experienced to you then hopefully they’ll be able to look at your code and understand and explain what is going on. If they can’t, you might need to look at your commenting / refactoring to improve this. When working professionally, you’ll get your code reviewed by making pull requests when merging in your current work to a branch. If you’re not in this sort of environment, seek out friends / other coders to take a look. (Send me a link to your code on Twitter, email or Facebook and i’ll be happy to take a look!).

Look at other people’s code

Getting people to look at your work is one way to write better code. Another is to look at other peoples work. We’re really lucky in this age that we can simply head over to GitHub and see the source of any type of project in pretty much any type of language. Or go to a Facebook group or forum with people posting examples of their solutions to problems. Take some time out each day to read other people’s code and analyse it; what do you like about it? Can you learn anything from it? What could be better? Picking up new tips and tricks from existing code will improve your own next time you encounter a similar problem.

Make sure you’re using version control

As mentioned above about merging your code in via a pull request, one simple way to improve your code is to make sure you’re using version control. Not only is version control handy if you want to undo a mistake, you can look back at your code over time to identify improvements or recall a way you completed a particular task. You can experiment with different techniques or approaches and throw away the changes if they don’t work. It also gives you the opportunity to work collaboratively with other developers be it remotely or with your immediate colleagues. Check out my Git Quick Start guide here.

Write tests

You might shy away from unit testing (like I did!) because it seems complicated or even unnecessary. But writing tests is important if you’re looking to improve the quality of your code. By it’s very nature, testing is there to make sure your programs do what you intend them to. If you are sure or don’t yet have the skill on how to write automated unit tests in your code you can always take a manual approach by creating a table of test data and expected results. You can then run your program using this test data and match this to your actual results. The aim is to get your program to fail so choose the wackiest, weirdest data you can and see how your program responds. By following this process you’ll make your program and therefore your code better and also gain an insight in how to write automated tests when you have got the hang of the process.

Learn more

My final tip for writing better code is a simple but essential one. You need to learn more about the language, algorithms, data structures, frameworks and tools that you are using and have at your disposal. You can’t refactor your code if you don’t know about a particular feature of a language (the filter function in our JavaScript example earlier on for example). By continually learning and improving your knowledge and skills you’ll be able to look at your current work and identify the areas that can be improved. Check out the latest courses, books, YouTube vids, blog posts and news to see what’s happening with your preferred technologies. Got your own tip for writing better code? Leave it in the comments below!