Do you usually write thousands of lines of code every day and end-up having no time to review your code? The answer will be yes for most of us. There can be serious consequences, if your code is not reviewed at least once, and that’s why we have Code Reviews also known as Peer Reviews!
If your team is looking to have a manageable, easy to understand and optimal code, then Peer Reviews is something you can’t miss.
In this article, I will list down very important points that can be applied to any programming language. This article will surely help programmers as well as code reviewers!
Table of Contents
Simplicity
Your code should be simple and easy to read. Look at the below code for instance.
bool status = GetAccountStatus();
if (status == true)
{
// Do Something
}
Variable name “status” is not much meaningful, having it named as “accountStatus” would make your code more readable. Also, if you look at the if condition, that can be simplified as –
bool accountStatus = GetAccountStatus();
if (status)
{
// Do Something
}
Exception Handling
Production bugs are the demons, who can ruin your day and sometimes nights 🙂 You might say, well our code is full of unit tests and we have manual testers as well. Well, there can still be hundreds of places where you are relying on the systems that feed information to your system. This is when exception handling comes to the rescue! Make sure to
- Wrap try-catch block around code that does input/output connections
- Write meaningful logs from within the catch blocks
- Have enough information logged which will help in investigations
- Decide if you want to just log the error or you need to hand over the exception to the calling code as well
- Close connections in finally block
Add Comments – only when required
Once, I was asked to work on a legacy project. When I got hold of the codebase, I was amazed to see the comments throughout the project. Every file had some comments written about important areas/logic. It really helped me a lot to understand the code. On the other side, there were some places where comments were unnecessary. Let’s take an example –
public UserInfo GetData(int userID){
{
//Get user data from DB
var record = GetUserInformation(userID);
// check if user exists
if (record != null){
return record;
}
else return new UserInfo();
}
In the above example, both the comments are unnecessary. Just by tweaking the variable names and function name, the code becomes easy to understand.
public UserInfo GetUserInformation(int userID){
{
var userInfo = DB.GetUserInformation(userID);
return userInfo ?? new UserInfo();
}
Leave a Reply