A Safe Way to Add Temporary Code
A quick tip to ensure your temporary code disappears when the sun sets.
We've all been there.
You throw some "temporary" code into your application while debugging some problem. You make a mental note to remove that code later. I mean, how could you forget, right? After all, if you were to forget and leave that code in place, it would annoy your users at best (MsgBox MyVariableIWantToInspect
anyone?) or introduce a logic error into your code at worst (let's just comment out this .CommitTrans
line temporarily...).
If you can accept that the only thing more permanent than a temporary government program is temporary computer code, then you can at least use some defensive programming to keep you from shooting yourself in the foot.
This Code Will Self-Destruct in 3...2...1...
A simple trick that I use when adding temporary code is to include a check of the current date.
Instead Of This:
Sub SomeRoutineICantMakeSenseOf(MysteriousValue As String)
MsgBox MysteriousValue 'Display the value in user env for troubleshooting
'-- Other code --
End Sub
Do This:
Sub SomeRoutineICantMakeSenseOf(MysteriousValue As String)
If VBA.Date = #2/26/2022# Then MsgBox MysteriousValue
'-- Other code --
End Sub
This ensures that the code will stop working tomorrow. You know, on the off chance you forget to remove it.
For Developer Use Only
For temporary changes that could cause problems in production, I add an additional check:
Instead Of This:
Do This:
If App.IsProd() Or VBA.Date > #2/26/2022# Then .BeginTrans
'-- Execute DML statement
'-- Execute another DML statement
If App.IsProd() Or VBA.Date > #2/26/2022# Then .CommitTrans
The concept in this example is that we want to be able to step through some DML statements (INSERT/UPDATE/DELETE) and see the results of each one without having to wait for the transaction to be committed.
This is not something we want to risk running outside of a transaction in a production environment, though, especially if we expect one of the inner DML statements to fail. I use my clsApp class to check whether my code is running in a production environment. That class defaults to treating every environment as a production environment unless you take explicit steps as the developer to mark your current user profile as a development environment.
Removing Temporary Code
There's a hidden benefit to using these date checks:
It's really easy to find all your temporary code by just searching your codebase for "#2/26/2022#".
I mean, that's a lot easier than searching for every apostrophe ('
) to find your temporarily commented code, amirite?
Referenced articles
Image by Marcello Savaris from Pixabay