sabato 21 gennaio 2012

Use late declaration

While developing code you will have to declare one or more variables before using it. If the language allows you to do so, declare them only when you are going to use! There are languages as C that require you to declare a variable at the begin of a code block, that could be far from when it is firstly used. There are other languages that allow you to declare a variable exactly where you are going to use it (Java, C++, Perl,...), and if possible you should get used to this habit. To explain why let us consider the following piece of pseudo Java code:

AuthToken login( String username, String password ) throws AuthException{
    AuthToken token;

    if( username == null || username.isEmpty() )
         throw new AuthException();
    else if( password == null || password.isEmpty() )
         throw new AuthException();
        // validate login and return a new AuthToken
        return token;

The code is quite simple: the method receives two parameters as input, check them againsta some rules and then wrap them into another object called AuthToken that is then returned. What is wrong with such piece of code? Nothing. But that is because it is Java. Now imagine the same code expressed in C++ language. Can you see what is wrong? The AuthToken object is build immediatly as it is declared and then there are two paths that will not use it (the two path that throw an exception). In such case the object will be wasted.
There is something more beside avoiding a memory waste: placing the variable exactly when you are going to use it makes it simpler to comment out a whole piece of code. In the above example, if you refactor the method to return a void, you have to comment out the return statement and also the variable declaration, and the two instructions are quite far. Now, while commenting out the declaration will mark the return statement as not valid, doing the vice versa will not and could lead to a situation where the code is correct even if the variable is still there.
Finally, declaring the variable where it is going to be used makes it simpler to refactor the code introducing new code blocks, and therefore new scope contexts.

Nessun commento: