Debug.Assert-s use the same error message. Should I promote it to a static variable?
- by Hamish Grubijan
I love Asserts and code readability but not code duplication, and in several places I use a Debug.Assert which checks for the same condition like so:
Debug.Assert(kosherBaconList.SelectedIndex != -1, "An error message along the lines - you should not ever be able to click on edit button without selecting a kosher bacon first.");
This is in response to an actual bug, although the actual list does not contain kosher bacon. Anyhow, I can think of two approaches:
private static readonly mustSelectKosherBaconBeforeEditAssertMessage =
"An error message along the lines - you should not ever be able to " +
"click on edit button without selecting a something first.";
...
Debug.Assert(
kosherBaconList.SelectedIndex != -1,
mustSelectKosherBaconBeforeEditAssertMessage)
or:
if (kosherBaconList.SelectedIndex == -1)
{
AssertMustSelectKosherBaconBeforeEdit();
}
...
[Conditional("DEBUG")]
private void AssertMustSelectKosherBaconBeforeEdit()
{
// Compiler will optimize away this variable.
string errorMessage =
"An error message along the lines - you should not ever be able to " +
"click on edit button without selecting a something first.";
Debug.Assert(false, errorMessage);
}
or is there a third way which sucks less than either one above? Please share.
General helpful relevant tips are also welcome.