venerdì 23 settembre 2011

Avoid the use of this, super and in general class qualifiers when not stricly required!

This can sound odd from me, that since my early days of OOP programming have always advocated the use of such qualifiers. The main reason I liked such qualifiers, and the main reason I presented to my students when teaching them OOP, was that the resulting code would be easier to read and, most notably, a lot of IDEs will bring up popups and code helpers to show you available completions. In other words, simply typing "this" will activate a popup that presents you with a list of choices between methods and fields to place in.
So what did change my mind? Why am I now advocating to avoid the use of qualifiers? Well, it is really simple: I switched back to some C code, and found myself comfortable while writing "unqualified" code. So I thought that in order to keep code clean and to get a more coherent syntax, avoiding qualifiers can help.
As an example consider the following piece of (imaginary) Java code:

   this.description = this.computeANewDescription();
   this.setTimeAndDate( super.getTodayDate() );
   this.setStatus( Status.STATUS_OK );

Now the above code can be rewritten in the following way, assuming you also use static imports:

   description = computeANewDescription();
   setTimeAndDate( getTodayDate() );
   setStatus( STATUS_OK );

Isn't it really much like a C code snippet? Apart keeping your fingers relaxed, due to not extra-typing keywords, the code is much more clean and can be read by any C developer.

Nessun commento: