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!