Mateusz Loskot :: hacking on, working out, living up

Const-correctness schizophrenia in GDAL

04 Mar 2010 | mloskot

Const-correctness rants are quite common topic of chats on #gdal IRC channel. Some of the pearls I’ve got printed in to my mind:

A: The lesson is I ought to get things right the first time. B: The issue with const method is that if you want to add lazy loading later, it can cause problems C: GDAL is rather painful to use with const correct code, unfortunately :( B: The solution is obvious: don’t write const correct code

Who’s right then, A or B?

I recall another motto from #gdal channel that sounds like “when unsure, do nothing” which has the following rationale:

especially when I realize afterwards that I’ve f**cked things because I neglected to follow the motto

Remembering these recommendations, it’s pretty clear why the const-mess in GDAL has happened. I’d conclude paraphrasing the motto this way:

I’ve f**cked things because I neglected to make a decision.

Now, poor GDAL beginner deadpickle, trying to find out (it’s me the evil) why compiler complains about his not-that-bad-written code, wandered to find and ask C gurus @ comp.lang.c and got the problem explained by Malcolm who wrote:

The problem is that, when C was first developed, there was no const keyword. So strings literal, which are constant, had to be non-const for backwards compatibility. This means that lots of programmers get lazy and omit the const, even from functions which don’t modify their string arguments. (There are also some subtle problems with const which means that this isn’t always a case of pure laziness). So a sort of solution is to discard the const qualifiers. However this is perpetuating the problem in your own code.

The motto stays in contradiction to a well-known best practice of const correct sooner than later. It’s way easier and cheaper to remove const-correctness once it turns out it does not express properly the actual design and contract than to apply it to existing codebase. Sometimes, the latter is even not possible making things f**cked up twice, in existing code base and in client’s code.

Fork me on GitHub