Ruby on Rails

Tips to write clean code

July 15, 2020

Author: Muhammad Faizan Anwar

Tips to write clean code

The main goal of this article is code readability and code style. This is important because usually, your code has to change or be reviewed by other people, and writing readably and in a good style makes these people's jobs a lot easier. That may be obvious but what’s less obvious is, it also makes your own job easier, because working on simple code is a lot easier than working on complex code, even while you are writing it, and the more readable code is always simpler.

1. Code Readability

Nowadays, there are two types of programming in the world. First is Simple Programing and the second is Good-Programing. Everyone can code the system by using programming fundamentals. Simple programming means we write code but not in a readable form. See the example below (Language: Ruby)

array = [100,1,3,44,66,99,14,19,24,26,28]
second_array = []
third_array = []
array.each do |a|
     if a % 2 == 0
          second_array << a
     else
          third_array << a
     end
end

If I ask you to tell me what the program does? It would be hard for you to tell because code is not readable. Actually this program separates odd and even numbers into two different arrays. Another example of this program is below: 

number_list = [100,1,3,44,66,99,14,19,24,26,28]
even_number_list = []
odd_number_list = []
number.each do |number|
     if number % 2 == 0
              even_number_list << number
     else
              odd_number_list << number
     end
end

This example is doing the same as the previous one, but the difference is this program is much more readable. Readability is very important because a programmer easily understands the code and can easily maintain the system. To achieve readability use meaningful names for variables. So readers can easily make sense of the code.

Now the question is why readability? For example, two developers are working on the same project. The first developer achieves login functionality. After that, a few changes are required in login functionality. The second developer will check the code that is written for the user login. If the code is not readable, then it will be very difficult and time-consuming work for the other guy to first understand the code and then fix the issue. Clean and meaningful code means the code is easily maintainable. 

Consider the following points to achieve maximum readability: 

Class Names

Classes and objects must have nouns or noun phrases names like Customer, Employee, Account, and Car. Avoid words like Employer, Processor, Data, or Info in the name of a class. A class name should not be a verb.

Method Names

Methods must have verb or verb phrase names like make_payment, delete_user, or save_user. Avoid names like payment, delete, save, etc.

Exception Handling 

In Ruby, exception handling is a process which describes a way to handle the error raised in a program. Here, error means an unwanted or unexpected event, which occurs during the execution of a program. If a function has a “begin” keyword, then it should be the very first keyword and there should be nothing after the "rescue" blocks.

An example of a program that handles error:

def raise_and_rescue
     begin
              puts "This is before Exception raise!"
              raise "Exception Created!"
              puts "After Exception"
     rescue
              puts "Finally Saved!"
end
puts "Outside from Begin Block!"
end 

# call the function
raise_and_rescue

Output: 

This is Before Exception Arise!
Finally Saved!
Outside from Begin Block!

Comment

If you are writing comments to show your point, you are doing a blunder. Ideally, comments are not needed at all. If your code wants commenting, you are doing something wrong. Our code should describe everything. Modern programming languages are English like through which we can easily describe our point. Meaningful naming can prevent comments. Comments should be legal and informative. Do not use the bad comment.

Unit Tests

Write the unit tests for code in the system. Tests must be written for each functionality of a system. By using tests we easily see the output of a function and easily understand the mistakes in our codes.

2. Code Style

In an ideal world, product code or code of different programs created by a particular company should look like it was written by a single person, even if it was written by hundreds. It also allows for more efficient creation of code and its maintenance, because you won’t have to think about the style of how you should name a variable.

Why must we care about code styles? Isn't it enough that our code works? Well, there are multiple reasons to care about our code styles. The first thing is consistency in our code. Any large code base with multiple development team members should look as if only one programmer wrote it. If a team agrees on a given style it can help keep the code consistent. If every member follows the same styles this helps keep source control changes to a minimum. For example, programmer A likes double quotes in his JavaScript code but programmer B likes single quotes. This can cause a headache for code check-ins and reviews. Once a code style is decided with a team everyone should follow it. This is not about preference but about writing clean and consistent code which is what professional software developers should do. 

When deciding a code style for your projects its best to start with language conventions. Some languages enforce certain styles while others are community-driven. An example JavaScript it is common to use single quotes vs double. There is a practicality to this style choice as it makes escaping quotes in HTML templating easier. In C# interfaces are commonly prefixed with and I. Now this some say is not needed as our IDE’s know its an interface and prefixing them is following Hungarian Notation which is no longer needed in modern IDE environments. Even though prefixing object types are not common anymore this is the convention with C# so it is widely followed in the community.

Code styles are great to have but when developers have a million other things to worry about like deadlines and bug fixes we tend to get sloppy with code style. Using tools called "code linter" or code style checkers can help. There is a wide range of tools but all work in a similar fashion. The linter checks for the source code for either potential bugs or code style violations. These tools usually come with a rule configuration file. A team can modify this file to the rules they desire then source control so all projects can benefit from it.

Coding style is made up of numerous small decisions based on the language:

  • How and when to use comments
  • Tabs or spaces for indentation (and how many spaces)
  • Appropriate use of white space
  • Proper naming of variables and functions
  • Code grouping an organization
  • Patterns to be used