Creation of a legible and clean code is important for several reasons.
First of all, we may increase the transparency of our solutions, making it easier for other programmers to work on our code. Second, looking after the code quality, we also reduce the amount of bugs in our application and simplify the way it is maintained. This article contains ten tips you can use to improve your code.
Table of Contents
Legibility of the code depends largely on the language we use and on the adopted coding convention. The general rule is fairly simple – our code should be transparent and readable, just like a book.
Names of variables, constants, functions and classes should be unambiguous and need to precisely describe the purpose of the given element. It would be much easier for us to find our feet in the code, if the applied nomenclature directly specifies the roles of particular elements of our application. Variables called x or y are very frequent – later on we have to spend much time to explain their functions.
For example, it is much better to use return G_EARTH_VELOCITY; than return 9.81;
Looking at the names, we should not only consider the roles of the functions, but also the values they return. Take the data validation function as an example. If it is supposed to return a boolean result, it is a better idea to name it isValid() than validate(), because such a name immediately suggests the type of the returned value. Name of the function should be a verb or include a verb. Classes, on the other hand, should be named with a noun or include a noun in their name, for instance: Customer, Account, Cart.
Rules applied to the name creation process are often defined by the coding convention we use. Therefore, it may be worth your while to learn more about them.
The most basic rule that governs the function writing process is “the less, the better”. Functions should be short. Obviously, there is no length limit, but the shorter the function, the easier it is to understand, debug, improve and develop it. Understanding and improving an ill-formatted function composed of 500 lines of code can be a real torment. Single-tasking is another important feature. Each function should perform only one task. This way, we can improve the readability of our code and facilitate its reuse in the future.
Considering the single-tasking rule, we should also take a look at the values returned by the functions. These values should always be of the same type. For example, a function should not return an object in one case and null in another.
Finally, we should analyze the function inputs. Here, the rule “the less, the better” also applies. An ideal amount of inputs is 0, but it is not always possible. Situation where the amount of inputs is higher than 2 should be avoided. The more inputs we have, the more difficult it gets to understand the operation of a given function, due to the amount of knowledge needed to figure out its structure.
Observance of these simple tips will help you to retain the principle of DRY (Don’t Repeat Yourself). Its assumptions are based on the avoidance of various repetitions, for instance writing (copying) the same or similar fragments of the code.
Law of Demeter is yet another rule. It says that the method of the given object may refer to:
- the same object,
- any parameter passed to this method,
- any object created by this method,
- any element, class the given method belongs to.
Due to the Law of Demeter, we may reduce the coupling. This way, changes in the structure of the given object do not invoke the need to introduce any changes in the client that uses this object.
Proper use of comments makes it possible to explain the less obvious elements of our code. We need to remember that an ideal code does not require any comments. For example:
// check if customer can buy products
if ($customer->isActive() && $customer->getAge() > 65)
is not as good as:
However, if we still need to use comments in our code, they should be brief and evident.
There are other kinds of useful comments as well, for instance:
Legal comments, e.g. // Copyright (c) 2014 Magento Inc.
Informative comments, e.g. // Returns an instance of a Customer object
Purpose-explaining comments, e.g. return 1; // it is default value
Warning comments, e.g. // very slow query, don’t use if you don’t need to
TODO comments, e.g. // @TODO rewrite this query
Code formatting is truly important, period.
Coding style and legibility have a huge impact on the application development process.
We need to look after the density of our code, both vertical and horizontal. Each line should be composed of a single expression and each block should present a single thought. Blocks should be separated with a single, empty line.
The length of a line is also important. It is assumed, that a line of the code should not exceed 80 characters. We also need to remember to use indentation and alignment to improve the readability.
6. Errors handling
First of all, use the exceptions. They make the code more legible and enable greater control over the behavior of your application. Creation of our own Exception classes is generally considered to be a good habit.
Each exception we throw should possess an appropriate context. This way, it will be easier to find out the meaning and location of the error.
We should also remember to avoid null. If we omit the check of a null at just one place, the whole application may work against our assumptions and generate bugs. Throwing exceptions is a better idea; we will be able to handle them easily at appropriate places.
7. Design patterns
In accordance with its definition, a design pattern is used to describe the solution to a known design issue. On the basis of the elementary classification, we may divide the design patterns into:
creational – describing the creation process of a new object;
structural – describing the structures of the objects related to each other;
behavioral – describing the behavior and responsibility of the cooperating objects.
With design patterns used in our project, we will be able to simplify and unify the applied solutions.
8. Coding conventions
Coding convention is a set of rules of good coding specified for the given programming language. There may be several conventions developed for a single language.
The choice is ours, but it is important to stick to the selected convention throughout the whole project, without any exceptions. Descriptions of most conventions may be easily found on the Internet. Some of the conventions we use at Divante are listed below:
9. Code review
In my opinion, the most important advice I can give you, is to introduce the Code Review mechanisms into your project.
Such mechanisms are based on systematic inspections of the code performed by other programmers, who check the conformity with the transparency rules described in this article, control the applied solutions and their compliance with the applied language/framework, as well as their optimization.
It guarantees an increase in the code quality and improvement of the programming team members’ skills. You also need to remember that Code Review is not testing. In my next article, I am going to describe the Code Review process implemented during one of Divante’s projects.
10. Choice of the IDE
And last, but not least. Some of you may remember the times when we used Notepad or Vime for programming purposes. Fortunately, it is the past. Nowadays, the market provides many advanced integrated development environments (IDE).
The choice of a specific product depends on the language we use, but most of the professional applications offer tools that enable the automatic code fixing, refactoring or the usage of various coding conventions.