sexta-feira, 9 de maio de 2008

Immutability and the good old 'const' keyword

With all the recent interest on C# functional programming and language integration of related concepts, one of the more interesting ideas is that of expressing immutability of an object.

An object is immutable if no methods beside the constructor can modify its internal state. Automatic verification of immutability is far from trivial, so many have been asking about how one could specify that an object is immutable at compile-time.

This would be interesting in multithreaded functional algorithm implementation, since we could potentially disregard parallelism concerns during function composing. All the shared data between functions was carefully protected simply by the fact that the data itself is immutable.

A couple of days ago I led myself to think: "Wait, isn't this what the const keyword in C++ was all about?". In fact, it's interesting how easily one could verify in C++ that an object was indeed immutable. Simply declare a const reference to an object and you only have access to const methods, which are methods guaranteed by the programmer that they won't change the object's internal state.

C# effectively abolished lots of extraneous keywords, in a quest to end unnecessary verbosity and functionality perhaps, but could it be that we're on the verge of witnessing a comeback of the so-called 'const programming'? No doubt it is an interesting way of solving the problem AND making sure that everything's verified at compile time. But it definitely increases the complexity in programming.

Sem comentários: