The other day I was testing a report that I’d written and it came up with an error.
The cell range being indicated had an end row that occurred before the start row.
I debugged the code to see what was happening and found that the start row was 14 and the end row was 13. This seemed strange, but warranted further investigation.
At this point I should also mention that this only happened for one particular data set. Most data sets generated reports without any issue.
The code looked like this:
tableRange = worksheet.Cells[startRow, startColumn, currentRow - 1, endColumn];
“Ohhhhhhhh, that makes sense,” I thought when reading the code. If the data set is empty, the start row and the current row are the same, this is clearly going to generate an issue. So I did what I thought was logical. I removed the “- 1”.
Now every report looked incorrect. The one that was failing was now generating, but it didn’t look good either. I clearly missed the line right above that said,
I ended up creating a constant equal to 1 named TABLE_RANGE_OFFSET and substituted it in that line of code. Now everytime I look at it, I’ll understand why it’s there instead of treating it as a 1 with dubious meaning.
And what was the actual problem? There was an error in the data set that prevented it from being processed properly. It wasn’t even a report issue. Now if that situation occurs — and it shouldn’t — it generates a friendly error message to the user explaining why the report can’t be generated.
So now I’ve been avoiding any sort of magic values wherever possible. I hate the idea that a piece of code might be deemed unreadable simply because it has a literal value embedded that no one remembers the meaning of.
Please be sure to, at the very least, comment the meanings of literals in your code.