Beautiful Blocks of Boilerplate
In my article, The ArrowKeyNav Routine, I presented a Sub that you can use to override the default handling of the up and down arrow keys on a continuous form. The problem with the routine as I presented it is that you need to call it from every control where you want to override the arrow key functionality.
Here's what that might look like in a form module:
Private Sub cbSupplierID_KeyDown(KeyCode As Integer, Shift As Integer)
ArrowKeyNav KeyCode, Shift
End Sub
Private Sub chkDiscontinued_KeyDown(KeyCode As Integer, Shift As Integer)
ArrowKeyNav KeyCode, Shift
End Sub
Private Sub tbID_KeyDown(KeyCode As Integer, Shift As Integer)
ArrowKeyNav KeyCode, Shift
End Sub
Private Sub tbListPrice_KeyDown(KeyCode As Integer, Shift As Integer)
ArrowKeyNav KeyCode, Shift
End Sub
Private Sub tbProductCode_KeyDown(KeyCode As Integer, Shift As Integer)
ArrowKeyNav vbKeyDown, Shift
End Sub
Private Sub tbProductName_KeyDown(KeyCode As Integer, Shift As Integer)
ArrowKeyNav KeyCode, Shift
End Sub
There are a couple of ways to reduce the amount of boilerplate code we need in this situation, but we're going to set that aside for the purposes of this article. So, for the sake of argument, let's just assume that there's no way to reduce the amount of code. Given that constraint, how can we increase the readability of the above code?
Joining lines of code with the colon character
We can join multiple lines of code using the colon character (:
).
<EOS> is used as a terminal element of the syntactic grammar to name the token that acts as an "end of statement" marker. In general, the end of statement is marked by either a <LINE-END> or a colon character.
Improving readability by joining lines
This technique is something you need to use with care. But, if used judiciously, it can increase the readability of your code.
In the sample code above, each Sub calls the same exact code:
ArrowKeyNav KeyCode, Shift
Actually, that's not true. If you look closely, you will see that the tbProductCode_KeyDown()
routine passes vbKeyDown
instead of KeyCode
as the first argument.
This difference is easy to miss using standard VBA formatting, though:
Making wrong code look wrong
If we join the lines using colons–and adjust the whitespace so all of our calls to ArrowKeyNav
are left-aligned–then the inconsistency that blends in above stands out like a sore thumb in the code below:
When viewed in the context of normal functions and subroutines, our block of boilerplate code clearly stands apart. This distinction helps increase the signal to noise ratio of our code:
Image by Alexander Stein from Pixabay