I was thinking the other day about magic numbers. I’m sure you’ve come across them. In fact, I’m pretty sure you’ve created them! Everyone who programs has. It might be a value like ‘1980’. What is that? It looks like a year, but it might not be. The general ‘fix’ for a magic number is to replace it with a named constant. The named constant tells the next reader of the code (who may be you) what the intention of the value is.

Replacing magic numbers with a named constant is a specialized case of the general problem of a lack of expressiveness. Nulls are another great example of a lack of expressiveness. You should avoid them wherever you can. Nulls don’t tell you anything about why the variable has no value. Is it missing, not yet assigned, or is there a bug that you haven’t yet found? It could be any of those things, but when you read a ‘null’ value in your debugger, it’s often the symptom of a larger problem that’s much harder to diagnose. Code should not only do what it needs to do, but it should explain why it’s doing what it’s doing, right there in the code. Not the ‘how’. I can read that. I can’t often read the why.

My first blog post here was about making methods very small. I also talked about giving these small chunks names that describe what they do, and in the process, reduce useless comments. This too, is expressiveness.

I’m not perfect at making my code expressive but I am getting better, and that’s all I would ever ask of any developer. A perfect example: twice in the past two days I was asked why a certain database field (CreditCount) that appeared to only need integer data was in fact a string. This field will eventually contain a character code. I should have been clearer. Not with a comment, mind you, but perhaps by changing the field name: CreditCountOrCode. Or, even better, making CreditCount numeric and adding a second field to handle the character code. If I had not still been on the project, someone likely would have changed it to an integer only to discover the reason in a few weeks or months from now and have to change it back. The later in the development cycle that you make fundamental changes, the more expensive it gets. No one wants that.

Leave a Reply

Your email address will not be published. Required fields are marked *