Ways to Write a Cleaner Code | Become a Better Programmer

8 mins read
Ways to Write a Cleaner Code | Become a Better Programmer
If you have ever worked on a development team, or have looked back at some of your old codes probably you would have come across a certain block of code that looked like if someone had a fight on the keyboard while the text editor was open. The messy syntax, cramped code, and unclear variable definitions could result in a pain to read. The situation worsens when you are stuck by the deadlines and are tasked with someone else's sloppy line of codes. Sometimes, it just moves with the flow as you are thinking and coding at the same time. Later, there is nothing that stops you from going back cleaning the code once again. With the help of a little more efforts, let's spend some time in learning how to become a better programmer by keeping your code neat, easily readable and well worth. Here are some tips that will help you to write a cleaner code naturally:

Conventions

Using a naming convention is a great way to start with. It helps in keeping things clear and lets you know exactly what you are working with. Naming convention basically means that you are going to call your variables by name that adhere to a certain set of rules. There are preset rules that people could go into but it can get hairy and most of the people don't agree on which is the best. Accordingly, for keeping it simple just try making it as clear as possible what type of variable it is and keeping the naming consistent. It can be as simple as adding variable names with their data type:
int numberOfChildren = 1;
float heightInCms = 70.54;

360 No Scope

The next big thing that follows nicely after naming conventions, is the usage of a convention for indicating variable scope. Again, there aren't any rules defined and every coder can have his own way of doing it as long as these are consistent throughout the code. It will make it simple for what can be used from where. One of the most common conventions is as under:
// Private and protected variables are prefixed with an underscore private
int _iScreenWidth = 900;

// Public variables are left as they would be normally public
int screenWidth = 900;

// Constant values are in all caps and separated with underscores
int SCREEN_WIDTH = 900;
Most importantly, feel free to follow any convention but make sure that you are clear with your code and have a consistent style as well. If someone else is looking at your code then they shouldn't be caught by the things for not being as they were expecting.

Say What You Mean

This becomes pretty straightforward and is probably the most common thing that you would see but also the easiest to forget. Eventually, the most frustrating thing that a developer faces looking at your code, is seeing a variable with a misleading name, or worse, named with a single letter. Let us try to understand this with the help of an example:
int getReaderType()
{
    if(r.type == t.new)
    {
        return 1;
    }

    return 0;
}
While this could look acceptable and is also functional but if someone found this in the sea of codes with minimum or no comments; it would sound like ‘why’ any of it is happening at all. The reader of the code shouldn’t have to read the function’s contents to know more about what it exactly does. Here, the user hardly has any idea what 'r' or ‘t’ could be. Moreover, this depends a little on the program's architecture. If in any case, you are returning something for indicating a boolean value, then you must return a boolean and not a number. Let's take a look at how we can clean it up:
bool getReaderType()
{
    return reader.type == ReaderType.New; 
}
Now, we rapidly know why the evaluation is being made as we understand what is being checked. We see that the reader type is being checked against an enum that holds all possible type of readers. We are now also returning a boolean value, that allows us to clean the syntax of the function by directly returning the result of the evaluation.

Whitespace Is a Nice Space

Often we find people writing crowded codes that are smashed together with almost zero space left anywhere, for becoming a better programmer you must not follow this. What do this results in? Nothing much than a code that is hard to read. From the previous example, if we try to write it with minimal whitespaces, it will look like this:
int getReaderType(){if(r.type==t.new){return 1;}return 0;}
The code above is perfectly valid, but it’s impossible to read. When it is combined with hundreds of similar pieces of code, it becomes so scary that no coder would like to even touch it. The use of whitespace could have incredibly powerful results, and normally it hardly has any downside. Although, in the case of languages like JS where the file size of the source code itself is important, the whitespace can add a few extra kilobytes, where you would expect your files to be small. But there are tools that can minify your files at the time of deployment so that you can reap the benefits of writing and editing in a neatly written code while getting the minimized source code to run on the server. So, in general, if you are writing many things together in a single block, then try grouping the lines of code into some logical pieces. Maybe it could have all of your code that might seem annoying at the time of writing but are very crucial when people try to find something in the large section of an unknown code.

Commenting Saves Lives — or At Least Headaches

Adding comments to your code could be invaluable and they can quickly divulge what a complex function is doing. Comments can be used to explain why certain things are required to happen in a certain order. However, excessive commenting has some cons as well. Too much commenting can have negative effects and can also result in sloppy code. Let us understand this with the help of an example:
// Function Started
/**
  * The function returns the number by randomly generating one
  * returns int A random number
*/
int getARandomNumber()
{
    // generating a random the number
    int randomNumber = Random.Range(0, 10);
    // return the generated random number   
    return randomNumber; 
}
// Function ended
These comments are literally out of control and are actually all the unnecessary lines of code. The comments should only be used when they are needed to describe the feature’s perspective.

Automating After 3 Times

If you are writing some technical lines of code it doesn't mean that it has to be less readable. The lines of duplicate codes are not only harder to read than a concise and elegant solution, but also helps in increasing the chance for an error. The tremendous thing about programming is that you can express commands in reusable, neat, and ingenious ways. Let us understand this with the help of duplicate code:
box1.x = 10;
box1.y = 20;
box2.x = 30;
box2.y = 20;
box3.x = 50;
box3.y = 20;
box4.x = 70;
box4.y = 20;
And here’s an approach that cleans everything up:
boxArray = [box1, box2, box3, box4]; 
for(int i = 0; i < sizeOf(boxArray); i++) {     
    boxArray[i].x = 10 + i * 20;     
    boxArray[i].y = 20; 
}
This approach is not only cleaner but is a more eloquent solution. Now, if you try adding another box to the array, the loop by default loops once more, as it checks the size of the array.

The Power of i

The tip is undoubtedly small but pursues on directly from the preceding step. When you have a code block with multiple loops one after the other; you would need different iterator variables. There has always been a debate about what we should use. However, the answer is slightly subjective. It starts making sense for declaring your iterator outside of the loop and reuse it. Let’s discuss it with the example below:
//declare variable initially
int i;
for(i = 0; i<10; i++)
{
  //loop stuff
}

for(i = 0; i<200; i++)
{
  //more loop stuff
}

 

Birds of a Feather Flock Together

As soon as your projects start getting larger accordingly your classes would have many variables, first, you should be keeping all of your variable declarations at the top of the page or at the very least all together somewhere. This helps in speeding up any kind of searching when you are in need of finding something crucial. Even though they are all together, it helps to arrange them in such a manner that it makes them even easier to comprehend. For example, grouping them all by what they are, could sound like a good way to go. It is quite likely that you'll have several types of the same object so that you can keep them all together in groups.

Keeping It Functional

The longer function definitions are quite an easy way of cluttering your code. Generally, it's always best for taking a look at what actually is being done. If in any case, the function is doing more than what its name suggests; probably the excessive functionality is likely to split out into its own functions. This can also help in the rest of your code as it becomes easier to look at. If a smaller functional piece can be used on its own- it means that other parts of your code can be used without any need of the duplicate content.

Related Articles