Naming Conventions Matter: Making Wrong Code Look Wrong

Joel Spolsky and Antonin Scalia join forces to help illustrate the importance of sensible code naming conventions.

"It is more like judging whether a particular line is longer than a particular rock is heavy."

Justice Antonin Scalia's famous phrase highlights the absurdity of comparing two fundamentally different things.  Consider the function below:

``````'This function calculates the difference between
'    the length of a line and the weight of a rock
'Returns the value rounded to the nearest tenth of a Scalia
Function ComputeRockLineDelta(LengthInInches As Double, _
WeightInPounds As Double) As Double
ComputeRockLineDelta = Round(LengthInInches - WeightInPounds, 1)
End Function``````

Sample usage:

This little reductio ad absurdum demonstrates the value of a strong naming convention.  By including the units in the variable names–LengthInInches and WeightInPounds–we provide a glaring visual cue that something is not right.  There is no sensical way to compare the length of a line to the weight of a rock.

Although, if such a feat were ever made possible, I propose the unit of measure for the difference be called a Scalia.

Making Wrong Code Look Wrong

My favorite story illustrating this concept is Joel Spolsky's seminal article, Making Wrong Code Look Wrong.

In yesterday's article, Beware the BETWEEN, I wrote about the dangers of using the BETWEEN clause to filter on date fields that include a time portion.  For the field name, I used the wonderfully ambiguous term, OrderDate.

A better date field naming convention would make wrong code look wrong in my first two examples.  Observe.

Right Code

The "On" suffix signals that we can "get away" with using the BETWEEN statement for our date filter.  It's still not ideal.  If any values accidentally get added to the table with a time portion then we could be in trouble.  In general, though, this code looks correct:

``````PreviewReport "OrdersByDate", _
"OrderedOn BETWEEN #10/1/2021# AND #10/31/2021#"``````

Wrong Code

Hopefully, seeing the "At" suffix on the OrderedAt field name will be enough of a reminder that this field contains a time portion.  The inclusion of a time portion means the use of the BETWEEN statement will almost certainly return unexpected results:

``````PreviewReport "OrdersByDate", _
"OrderedAt BETWEEN #10/1/2021# AND #10/31/2021#"``````

With a strong and consistent naming convention–and enough experience working with it–we can make it harder for bad code to slip by unnoticed.  For example, queries that use the BETWEEN keyword in combination with a date/time field ending in the At suffix should send up red flags.

I mean, that would be, "like judging whether a particular line is longer than a particular rock is heavy."

External references

Image by Magnascan from Pixabay

All original code samples by Mike Wolfe are licensed under CC BY 4.0