Thank you for your donations!   Download the book!   Public source code repository  

const considered (mostly) harmful

I started salvaging algebraic notation (AN) parser from top down (as posted by the end of August), when I stumbled upon a serious issue with iterators. My fault for sure, but what was peculiar about it is that I was somewhat subconsciously trying to write Python in C, and longing for more expressive language. In fixing this issue, I also had to unlearn quite a few things, and re-learn some I mostly forgotten. After a few iterations, I ditched static variables inside function, for input/output parameters. While, at first, this looks like a eyebrow-rising design, it's thread safe, clear how to use it, without need for an awkward initialize_iterator parameter.

While I was fixing iterator in string utils, I stumbled upon another issue, variable and parameter names weren't consistent. So, I started fixing those, when in the middle of the changes I stepped into a turd of a const-correctness, especially involving pointer-to-pointer parameters. Looks like I'm not the only one; what is actually surprising is how long code peppered with consts lasted. I was searching for answers, and I found out it's by (bolted-on) design, from the very onset.

Some pondering later, I figured out that const is not meant to communicate constraints of underlying function algorithm, but to designate initializer data (strings, arrays, tables, ...) which won't change as such, and so do not slap const carelessly onto every thing in sight.

So, rules for applying const I now use are simple:
1. const is mostly for parameters
2. char * parameters, and any pointer to simple* struct, union
3. module or global variables, if used for initialization, and won't change
4. anything else should be const free

* simple in this context means it does not contain pointer

This change has already being made, and it's refreshing to see code free-ed from all that const noise. Now, I'm finishing renaming of variables, parameters, while I also occasionally double as a plumber (no, not by saving Princess Peach, but by fixing some (memory) leaks). After that I have to do a couple of  relatively simple TODOs, then re-implement a few iterators. After all that, I'll get back to my original task, re-doing parser. I won't try to predict how long this all will take, I'm notoriously really bad at reading from crystal ball.

No comments:

Post a Comment