I mean would it be bad practice if I want an if statement to have an else, but there is a nested if statement “in my way” so I use a blank else statement such as “else ;” or “else { }” to escape it?
ex:
if (lsvAddons.SelectedItems.Count > 0)
foreach (ListViewItem A in lsvAddons.SelectedItems)
if (Addons[A.Index] != null) Addons[A.Index].DoHelp();
else { }
else Console.WriteLine(_GenericHelpString);
vs:
if (lsvAddons.SelectedItems.Count > 0)
{
foreach (ListViewItem A in lsvAddons.SelectedItems)
if (Addons[A.Index] != null) Addons[A.Index].DoHelp();
}
else Console.WriteLine(_GenericHelpString);
Or even:
if (lsvAddons.SelectedItems.Count > 0)
{
foreach (ListViewItem A in lsvAddons.SelectedItems)
{
if (Addons[A.Index] != null)
{
Addons[A.Index].DoHelp();
}
}
}
else
{
Console.WriteLine(_GenericHelpString)
}
Braces are your friend.
You’ll be ahead of the curve if you resist the urge to omit braces. The third form is completely unambiguous, easier to read, and will help you avoid inadvertant errors. I don’t know about you, but I can understand the behavior of the third form right away .. the first two forms require more thinking and mental parsing to get right.
Many developers try to get rid of braces and use the implicit form of
ifstatements. Unfortunately, what do you do when you run across something like:Did the developer simply indent incorrectly? Or was the intent to have both methods part of the same condition? It can be hard to tell after the fact … and is a leading source of defects. Here’s an even worse example:
Do you notice the subtle mistake here?
You’re much better off in the long run if you make your code unambigous and less prones to these kinds of problems.
Often developers argue to omit braces so that their code is shorter and easier to understand. Now, there’s certainly merit to avoiding long methods (some even argue that methods should always be 1-screen long) … but I don’t think the risk introduced by this kind of brevity is generally worth the reward. Keep in mind, there are ways to restructure methods to avoid excessive nesting – and they often gain you more in readability than omitting braces do.
My personal mantra is: