Sunday, November 23, 2008

Programming without const

I've just learned that java does not have a const keyword. I am very inexperience with java. I learned it well enough to complete my Senior Design project at WSU but that was it.

One of the first lessons learned by new C++ programmer is that const correctness is your friend (and that it's hard to add in after the fact).

Java final does something similar for integral values but is almost completely worthless for Objects.

final int i = 10 == const int i = 10;
final Foo f = new Foo(); != const Foo* f = new Foo;
final Foo r = new Foo(); == Foo *const f = new Foo;

Many C++ programmers have never even used a "pointer to const". It's just not that useful.

To top all this off. There was a request put into Sun to add a const semantics to java. The request was closed. It looks like java is not going to get const anytime soon.

Java has a parallel mechanism. Wrap objects in a light interface and don't make the mutating methods visable. You can achieve the same const semantics and more, obviously though more work is required.

To be fair C++ const semantics aren't perfect either. The const is only shallow.

const struct Bar
{
int i;
int* j;
} bar;

This is equivalent to:

struct Bar
{
const int i;
const int* j;
};

Perfect const semantics would be equivalent to this

struct Bar
{
const int i;
const int * const j;
};

The new D language has perfect const semantics.

You can learn more here en.wikipedia.org/wiki/Const_correctness