mercoledì 21 settembre 2011

Avoid naming variables with the name of their type

Often you can see code where variables are named after their type, such as for instance:

      CrudDAO crudDAO = new CrudDAO();
      String  string  = "Hello";

and so on, you get the idea. While this makes sense if you are writing an "Hello World" program, it does not scale when you have complex and long listing sources. In particular it becomes harder to refactor such code, because if you want to change such variable types, you have to change their names too. While this can be performed by an automatic refactoring tool, it almost always requires a manual intervention. Therefore, choose mnemonic names that have a correct meaning regardless of the specific type they belongs too, such as:

      CrudDAO dao      = new CrudDAO();
      String  message  = "Hello";

In the above code, it becomes very easy to change the type of the "dao" variable to another instance letting it representing what it means: a Data Access Object. Similarly, if the "message" variable is changed to a Char array, you don't have to change its name to reflect such change, since the name is much more meaningful than a simple "string".

Nessun commento: