Code that doesn`t suck – How to write better Code

Anyone can learn to program, but not everyone can write better code. I start from this premise as an inspiration to write this article, as it has touched me sometimes continuously revising, editing, etc. or code that someone else wrote. On many occasions this experience has been disastrous, so I want to present this article that brings a set of techniques to improve readability and thus manageable code.

Manageability

The purpose of writing maintainable code is to facilitate the understanding of it both for ourselves and for other developers. This, of course, makes it less difficult the incorporation of new staff to the project, reduces complexity by including new modules and reduces time in our planning.

Techniques

The techniques presented here are those I consider most important, some were drawn from MDSN, Wikipedia and my experience.

According MDSN (which I agree), there are three types of techniques:

  • Naming
  • Comments
  • And Format

Naming

The names much influence the interpretation we give to the symbols that we create. For example, a variable called “sum” implies that we stored a sum. However, programming must be more specific, the idea is to provide as much information to the reader without relying so much on the context. For example, if we call the variable “sumMoney” instead of “sum”, meaning we get a better understanding of that variable.

write better code

It is also very important to use a consistent naming convention. The most commonly used are “Camel Case” and “Pascal Case”. Camel Case proposes that names begin with lowercase and then concatenate each word capitalized the first letter (e.g. calculateTotalTax()). Pascal Case proposes to use the first letter capitalized (e.g. CalculateTotalTax()). It would be better if you use one technique at a time, not several in the same project, preferably uses the convention that uses language in which programs or framework you use.

Something I see a lot in the world of programming is the variety of languages in which people program. We must be consistent in the language of our project, if not see things like “eliminateDuplicates()“, and then two lines below “findUser()“, and in the worst case “destroyFriend() “. Let those “byebyeFriend()” for movies.

Avoid using abbreviations. Of course everyone knows what you mean with “num”, “min”, “max”, but in cases where it is not so obvious, it is convenient to write the whole word.

Here are some more specific techniques to improve our symbol names:

Functions

  • As I said earlier, avoid ambiguity, calculateAverage() is better than calculate().
  • Avoid redundancy. For example, an attribute of the Person class, should not be called “RespondentID” with only “id” enough.
  • Use names that give an idea of the value they return, for example, getName(), generateRandomString().

Variables

  • Boolean type variables should start with the prefix “is”. As almost always believe to be evaluated in the conditional (eg if), greatly improves readability use something like if (isComplete) {.
  • Use names, if possible, to give an idea of the data type of the variable, for example, age: int, name: string, height: float.
  • Avoid using names with special characters such as $,%, to indicate the data type
  • Avoid using names like a, b, c, d, i, j, k; use names that have meaning
  • This depends heavily on language, but usually, the constants are named in capital letters, in other cases use “_” to separate words and others are Camel Case but carry the letter “k” prefix (eg PI, SERVER_URL, kDefaultPort). The important thing is to use a single convention.

Comments

Comments help you document your code. This is important because no matter how good the names of our variables, functions or classes, there is always required an explanation to better understand the logic of the code.

Some techniques I recommend:

  • When you add new code, be sure to keep updated comments.
  • Write comments on the top line variables, functions, classes, etc. Avoid writing them at the end of the line, right next to the statement. However this type documentations are good if the line is short and the comment is separated by a tab.
  • Before making deploy or release of your project, removes comments that no longer apply,
    for example,  // TODO: call that function
  • Use complete sentences when writing comments. The idea is to reduce ambiguity.
    comments like // comp
  • Discuss the code required as soon as possible, leave it for later could make you forget your purpose. In college we used to joke, “Today God and I know what I programmed here, tomorrow only God knows.” :D
  • It is true that developers enjoy a kind of black humor that characterizes us, some programmers even lead to code. Avoid, superfluous comments make us lose time on unnecessary long readings.
  • Comment only what is not obvious in the code, avoid overloading comments.
  • Use conditional comments and especially in cycles, these are crucial points where it costs more to understand the why of things. For example,  // if you are finished is a good comment if (isCompleted)
  • Always leave a space after the comment delimiters.
    For example, it   // this is a comment   :)  is easier to read than //this is bad comment :(
  • Always use the same style comments. By this I mean writing, punctuation, structure. Consistency is the key.

Before release or deploy your project, use a documentation generator. Such tools usually generate a collection of HTML files from comments in the source code

Format

The format of the code makes logical organization startle. This favors our understanding (when we no longer remember we did – because it happens… :P) and understanding of other developers.

Some techniques:

  • It uses a set of spaces for indenting amount. I recommend following the convention of each language: JavaScript is usually use 2 spaces, in-objective C (yes, I have commented) Java, C #, Swift, you typically use 4 spaces.
  • Aligns the keys with code blocks that close, and uses the convention of language: JavaScript open right in C # on the line below.eg:
// javascript

if (name === "nipun") {
  // do something
}


// C#

if (String.Compare(name, "nipun"))
{
  // do something
}
  • Write a number of lines in the code or comments such that reader need not having to scroll to read. Methods are often used about 30 lines long and not wider than the 80 columns.
  • Leave a blank line before and after each operator, improves visibility:
function compare(operator1, operador2) { 
 if (operator1 > operador2) {
    return true;  
 }  
return false;
}
  • Uses else only when necessary. If there are no more options to evaluate after if, you can return once (See code example above).
  • Leave a space after each comma.
function operate(operator1, operador2, operator3) { 
 // do something
}
  • Create paragraphs of code leaving blank lines, so you can provide greater understanding for lines that relate to each other:
// triangle

var triangle1;
var triangle2;
var triangle3; 

// squares

var square1;
var square2;
var square3; 

operate(triangle1, triangle2, triangle3);
operate(square1, square2, square3);
  • Avoid writing more than one statement per line (if possible).
// not very good

if (!closed) return;



// more readable

if (!closed) {

return;

}
  • Code logically divided into separate files. (Eg each class in separate files).
  • Do not use numbers literally uses variables or constants to give it meaning.
// ex

for (var i = 0; i < 7; i++) {

// algo

}



// better

const count= 7;

for (var i = 0; i < count; i++)

{

// algo

}
  • Use switch wherever applicable, avoid those if following if after if, “n” number of times

Some special considerations

Use them wisely when they apply:

  • Use variables necessary size. In c # sometimes a short(16 – bit integer) may be sufficient and not need a int(32 – bit integer).
  • Keep the scope of a variable-as short as possible to avoid confusion.
  • Functions and variables used for a single purpose.
  • Use only the amount of public attributes in a class as needed, it is better to create private attributes to favor the encapsulation.
  • Avoid writing SQL code application side, use an ORM.
  • Avoid casting objects and when necessary and nontrivial says the reasons.
  • Capture errors using try-catch-finally. It will help make your application more robust.
  • Use logs, will help you identify errors.
  • Create your own exceptions inheriting from “Exception” or its subclass that best applies (SQLException, IndexOutOfRangeException) to your case.
  • Avoid global variables as much as possible.

Conclusions

Using consistent techniques and good programming practices will improve your code and therefore manageability, understanding, extent and quality of your application.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top