venerdì 30 settembre 2011

Qt: General Purpose Database Connection Dialog

Oggi ho inserito nel Wiki Qt una pagina che mostra una dialog window generale per gestire una connessione ad un database. La dialog presenta all'utente una combo box con i tipi di database supportati (nomi dei driver) e una serie di campi che l'utente deve compilare per impostare le proprieta' di connessione (username, password, porta, host, ecc.). 



La dialog non attiva il pulsante di connessione fino a quando tutti i dati sono compilati e presenta anche una stringa URL riassuntiva della connessione (ovviamente senza la password!).
La dialog emette un signal con la connessione stabilita qualora questa avvenga con successo. 
Infine la dialog supporta la modalità auto-connect: i campi possono essere precompilati prima che la dialog sia visualizzata (es. da valori di default) e se si specifica l'auto-connect mode allora la dialog tenta immediatamente la connessione, che se avviene con successo non viene nemmeno mostrata all'utente. Di conseguenza è possibile associare la dialog ad una azione di connessione al database che chieda informazioni all'utente solo se i dati di connessione sono incompleti o sbagliati.

giovedì 29 settembre 2011

Qt Creator e gli hint nascosti

Qt Creator, l'ambiente IDE di riferimento per lo sviluppo Qt, ha dei code-hint nascosti che vengono attivati con la combinazione di tasti ALT+ENTER. Ad esempio, dopo aver dichiarato un metodo nell'header di una classe, facendo ALT+ENTER con il cursore posizionato sul nome del metodo stesso si attiva un menu' a tendina che permette di aggiungere l'implementazione del metodo (stub auto-generato).

Questo comportamento, non documentato, è variabile a seconda del membro su cui si attiva ALT+ENTER. La cosa strana è che il menu' C++ dell'IDE, che è gia' molto scarno, non riporta affatto queste opzioni. Spero anche che venga agigunto presto un sistema per l'autogenerazione dei getter/setter, e so che una richiesta è già in coda da diverso tempo per questa feature.

mercoledì 28 settembre 2011

Do not be public!

This is a well known rule of the OOP: encapsulate!
What this really means is that, as in all computer science fields, you should start giving no-rights and then adding a few allowance. In other words, each property you declare in a class should be private, each method should be final/const and so on. Of course I'm excluding the struct-alike objects from this paradigm.
Why be so reluctant to use protected? Well, you will be able to give up your rights later, and to convert your private field to protected, or even to public. You will be able to give others the capability to overload your methods, but if you don't have a real need to allow them to, don't!
Consider the following example:

     public class Foo{
         protected int counter = 0;
       
        public void sendEmail(){ // do stuff }

        public Foo(){
               counter = 10;
               sendEmail();
        }
     }


What is wrong with this kind of code? A lot of things... First of all the counter variable can be accessed directly from Foo subclasses, and this could not be what you want. Imagine you want to assure that all instances of Foo (and of its subclasses) have a counter that is initialized to 10, how can you impose this? You have to declare counter as private and provide no setter method for it. Leaving the field protected is a call for troubles.
A worst error in the above code is the sendEmail method signature, which is not final, and therefore can be overriden. Why is this wrong? Because the constructor of Foo will call a polymorphic method, and trust me, this can lead you to endless debugging sessions!
Summarizing, I can say that you should declare everything private, and when it is not private, declare at least final, and only when you are sure of what are you doing, allow direct access to methods/fields.
Now consider what happens with C++ with regard to methods: each method declared not virtual is automatically declared as final in Java. In other words, C++ does it right: it gives you the stricter behaviour on methods. I agree with you when you say that having to write "virtual" for each method is an extra-typing that can be avoided, but it is the only way to avoid awkward errors and is a good way to prevent you to release an API that is broken.

Qt: creare un nome di file con la data del giorno

Un trucchetto banale per costruire un nome di file che includa la data odierna nel proprio nome:


QString FileNameHandler::todayFileName(){
    QDate today = QDate::currentDate();
    QString relativeFileName( "data_" );
    relativeFileName.append( QString::number( today.month() ) );
    relativeFileName.append( "_" );
    relativeFileName.append( QString::number( today.day() ) );
    relativeFileName.append( "_" );
    relativeFileName.append( QString::number( today.year() ) );
    relativeFileName.append( "_" );
    relativeFileName.append( ".txt" );
    return relativeFileName;
}
Ho inserito questo esempio anche nel Wiki ufficiale Qt

domenica 25 settembre 2011

Do not be afraid of using structs for you (internal) implementations!

With the advent of OOP languages, developers seem to have forgotten that not everything need to be a fully implemented class. In a typical program you have bunch of data that must be collected together, but that not always needs to expose all the OOP features such as encapsulation (i.e., having hidden properties), accessors (i.e., getters and setters) and a polymorphic behaviour. Sometimes you need only to store a few fields together, for internal uses and just for your own convenience. A typical example is when you deal with external resources, for instance something that comes from an underlying software/library. In such cases, it is probably you will not be able to change the data that is passed back to you, but you have only to read and take actions depending on its value. In this scenario, it does not make any sense to build a fully object with a lot of getters/setters/constructors/destructors, a simple struct-like packaging will suffice.
Another example is when you have to deal with a few annotations at the same time; instead of accessing each annotation to get each value, you can pack values into a struct-like object and access such fields directly. Since you are not supposed to change an annotation at run-time, creating setters does not make sense, and therefore creating getters does not make sense either. So just skip them and use a struct!
I know that your OOP-soul is screaming about the above, but trust me, each method you add requires a new stack allocation (if not inlined, of course) and does not provide you with much more control than you require. After all, consider the following simple example (Java code):

class Person{
       private String name;
       private String surname;

       public String getName(){ return name; }
       public void   setName(String n){ name = n; }

       public String getSurname(){ return surname; }
       public void   setSurname(String n){ surnname = n; }
}


How often have you changed the accessor methods? I guess that for almost the 95% of you beans you don't have to overload the generic logic of getters and setters. In such a scenario, having the following is much simpler to write and to use at run-time:

class Person{
       public String name;
       public String surname;
}



There is of course a problem: if you need to change your accessing rules, you will not be able without breaking compatibility. In other words, once you expose a struct public property, you will never get it back!
However, as you can see, the class is not public, that in Java it means that it cannot be accessed outside the current package. In other words, the class does not represent a public API, but a private one, and you are always able to change it depending on your wills without even having clients to notice it.

There are also other cases when using struct-like objects is allowed, and an example is when your OOP API is an adaptor of an external API. An example can be found into the SWT Java GUI API, that being a kind of reimplementation of the Operating System API, it make a deep use of structures because they maps really well into the Operating System data structures.

In conclusion, the main idea of this article is that structs are good, but must be used with caution to avoid to make public something that could requires soon or later a different control path. But if you are sure you are using objects for your internal implementation and/or to map other languages/libraries structs, use them without being scared of!

sabato 24 settembre 2011

Che ore sono? Come Windows può forzare un jet-lag in Unix!

Sui sistemi dual boot Windows/Linux e/o Windows/Unix puo' capitare che all'avvio del sistema *nix alcuni file e directory risultino avere una data di creazione nel futuro, nonostante la data del sistema *nix sia impostata correttamente. Tipicamente la differenza è solo relativa all'orario, che si trova di alcune ore nel futuro. La motivazione dietro a questo problema risiede nel modo in cui Windows gestisce l'orologio di sistema: il sistema Microsoft impone infatti che l'orologio sia impostato come ora local. I sistemi *nix invece all'avvio impostano il time zone corretto prima di far partire tutti i servizi. Quello che succede è quindi che al boot di un sistema *nix l'orologio si trova in modalità local, quindi con un timezone non impostato. Il sistema *nix provvede alla creazione degli pseudo-device, /proc, ecc. con l'ora sbagliata, e poi, appena applica il timezone, si trova a correggere l'orario. Riporto un link ad un interessante thread che spiega questo problema.

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.

Benchmarking tools

Solitamente per testare le prestazioni I/O di un sistema uso bonnie++, ma di recente ho scoperto un altro tool piuttosto interessante: filebench.
La cosa interessante di questo strumento è che presenta all'amministratore una shell che consente l'esecuzione dei vari comandi. Altra cosa interessante è che il tool viene installato con una serie di personalità differenti, ossia di workload pre-configurati per i test.

mercoledì 21 settembre 2011

C++11

E' ufficiale, la nuova release delle specifiche C++ (denominate C++11) è stata accettata! 
Il linguaggio subirà notevoli cambiamenti, fra i quali:
  • possibilita' di inizializzare staticamente le variabili di classe, marcando i costruttori come espliciti
  • possibilita' di definire delle espressioni da usare al posto di costanti, una sorta di macro valutabile a run-time
  • possibilità di marcare dei metodi come  final  e come ovveride per specificare e controllare meglio dove e come si sovrascrivere un metodo di classe base (e se questo sia possibile)
  • definizione di un puntatore nullo, nullptr, che sostituisce il vecchio (e compatibile) valore 0
  • ciclo foreach simile come sintassi al ciclo Java
  • utilizzo dello specificatore auto per lasciare al compilatore il compito di comprendere il tipo di una variabile (type inference)
  • possibilità di inizializzare delle liste di oggetti staticamente
  • funzionamento di sizeof anche per tipi innestati
  • multihreading
  • lamba calculus
Forse la novità piu' sconvolgente, almeno secondo la mia opinione, è proprio l'ultima, che conferma come il calcolo funzionale stia sempre piu' prendendo piede (o riprendendo piede!).
Per una lista piu' dettagliata delle modifiche al linguaggio e alla libreria si vedano i seguenti link:

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".

martedì 20 settembre 2011

Qt Project


E' di qualche giorno fa l'annuncio ufficiale del Qt Project.
Finalmente, dopo tanti anni di discussioni e polemiche sul licensing delle Qt (chi non ricorda la storia di Gnome e Stallman che incita De Icaza?) si e' deciso di dare a queste fantastiche librerie grafiche una foundations che ne guiderà lo sviluppo e la gestione. Ci si muove quindi velocemente verso una piena liberalizzazione di questo ottimo framework di sviluppo.

The Java Beans specification sucks!

Ok, the title is quite harsh, but it is so true...
The Java Beans specification imposes that each object property (i.e., variable) is accessed thru a couple of setter and getter method. In particular the method must be named with set/get prefix (lowercase) followed by the name of the property (with the first letter capitalized and the remaining as the original name). The return type and the arguments depends on the type of the method (often called accessor): in the case of a getter there are no arguments and the return type is of the same type of the property; in the case of the setter there is no return type and there is a single argument of the same type of the property.
As an example, the following is a correct Java Bean class definition:

class Person{
      private String name;
      private String surname;

      public void setName( String newName ){ name = newName; }
      public String getName(){ return name; }
      public void setSurname( String newSurname ){ surname = newSurname; }
      public String getSurname(){ return surname; }
}


As you can see the "name" property generates the "setName" and "getName" methods, as well as the "surname" property generates the "setSurname" and "getSurname" methods. All the getXX methods have a return value of the same type of the property and accept no arguments; all the setXX methods do not return any value and accept a single argument of the same type of the property they refer to.

Why I don't like this naming convention?

Let's start with the naming schema: while it is clear that I have to separate a getter name from the setter one, why should I have the get prefix? I mean, if I want to access the "name" property, that is exactly what I want to type. What is the simpler and beautiful code between the following?

      person.getName();     // Java Bean style
      person.name();        // Qt style


The latter does exactly what I want: I want to access the name property, so I don't want to explicity say "get the name property", but simply "the name property". Easier to type, simpler to read: I'm accessing the person name, I don't need to emphasize that I wan to "get" the person name because it is implicit that I am asking the person's name!
On the other hand the setter can remain the same, so that my bean becomes:


class Person{
      private String name;
      private String surname;

      public void setName( String newName ){ name = newName; }
      public String name(){ return name; }
      public void setSurname( String newSurname ){ surname = newSurname; }
      public String surname(){ return surname; }
}


A drawback of this approach is that using a standard prefix I have all the method grouped together: all the getXX and all the setXX. Removing the get prefix I find only the setters grouped together, while the other methods are sorted as the property names. This can be boring only if you are used to inspect a bean by means of reading the getter method names and not by reading its documentation.
Moreover, it is not clear how to behave when you have boolean properties: should you use "is" or "has" prefixes in the method names? A lot of framework seems to deal with the "is" convention, but I'm sure that a getter method called "isMoney" to return true in the case has still money sounds awkward even to the stricter Sun's engineer.

Anyway, another big, even huge problem of the Java Bean specification is that it does not consider side-effects. How can you test a setter method? You have to create a getter method! While this can sound ok to you, it does not look very good to me. When you execute a method call like:

    person.setName( "Luca" );

how can you assure that the name has really been set to "Luca"? You have to call getName() and test the two values. While setter and getters are usually simple and straightforward methods (those that can even be inlined), a lot of things can go wrong while in the execution path of one or the other. What is the solution? To have a setter that can return the actual value of the property, so that it is defined as returning the same type of its parameter. In other words:


class Person{
      ...
      public String setName( String newName ){ 
          name = newName; return name; 
      }
      public String setSurname( String newSurname ){ 
         surname = newSurname; return surname;    
      }
}


In this way the setter methods represent a single unit of testing, therefore can be tested as they are without requiring anything else (in particular a gettere method). Moreover in this way the classes are exposing to the outside world a clear side effect of the setter methods.

In conclusion I disagree with the Java Bean specification mainly for:
- their naming convention;
- their definition of setter method.
The worst thing in the whole story is that you cannot even think to change the Java Bean convention to use a different name schema or even to change the return type of the setter methods. This is due to the fact that a lot of Java frameworks adopt reflection to inspect and access properties, and while doing so they will stupidly search for setter methods that return void!

Big Endian vs Little Endian

Una delle migliori spiegazioni visuali del problema!