tags:

views:

237

answers:

10

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)
}
+7  A: 

Use the third formatting.

JungleFreak
I can only second those guys saying the third one is the formatting I would also prefer.
Jim Brissom
Although the second one isn't too bad. In my opinion, anything except the first.
luiscubal
The third one looks like it was invented by people paid for by lines. I much prefer the second one.
romkyns
+6  A: 

If you're asking which is nicer, cleaner code, then the last one!

Fiona Holder
+8  A: 

An empty code block is bad practice.

else { }
Larsenal
+1  A: 

Use curly brackets ({ and }) to specify to which if your else belongs. By default, it belongs to the if closest to it in the same scope (the curly brackets). Using brackets also improves readability for you in the future and other developers which might read it.

So, use your second formatting to solve you problem.

if (lsvAddons.SelectedItems.Count > 0)
{
    foreach (ListViewItem A in lsvAddons.SelectedItems)
        if (Addons[A.Index] != null) Addons[A.Index].DoHelp();
}
else Console.WriteLine(_GenericHelpString);

However, I would prefer the third example you gave, for readability.

Virtlink
I think he knows that, which is why in the first example he is putting a blank else to make it clear which if they belong to
Fiona Holder
@Fiona He hadn't explained the question when I started answering. I've updated my answer now.
Virtlink
Have you used Visual Studio before? It indents the code automatically *and correctly* so it always shows which `if` an `else` belongs to.
Timwi
+17  A: 

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 if statements. Unfortunately, what do you do when you run across something like:

if( someCondition... )
    DoSomething();
    DoAnotherThing();

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:

if( someCondition );
    DoSomething();
    DoAnotherThing();

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:

  1. Make it correct.
  2. Make it clear.
  3. Make it concise.
  4. Make it fast ... in that order.
LBushkin
I just can't help but think that the larger the block of code in my class files the more difficult to understand it will initially seem to people reading it, even if it is spaced out.
Blam
Also wondering what your thoughts are on same line, aka: `else Console.WriteLine(_GenericHelpString);`
Blam
+1 for the mantra
Larsenal
@Blam: It's the same thing. Don't omit the braces. I've seen many defects that resulted from developers misunderstanding the intended scoping or cohesion of statements. Trust me ... those extra two characters will save your trouble in the long run.
LBushkin
Uhm, have you ever used Visual Studio? It is actually *really* difficult to get the indentation wrong in that case — you’d have to do it deliberately!
Timwi
Who says I'm using VS? ;) (sup monodevelop)
Blam
And thanks for the reply, I guess I should start bracketing my work.
Blam
@Timwi: I do indeed use Visual Studio, but your assertion that it's really difficult to get indentation wrong is misplaced. The code reformatting features of the editor don't catch all problems, and using them as a crutch can backfire when you work in an IDE (or language) that doesn't behave the same. **Tools are not substitutes for good habits.**
LBushkin
@LBushkin: Yes, they are. Using the wrong tool is a bad habit. Using a good tool is a good habit. Furthermore, in my 5 years of using Visual Studio I have never seen the autoformatting feature mis-indent a statement after an `if` in the way you describe. @Blam: If your tool gets the indentation wrong and thus confuses you, then you are using the wrong tool for programming.
Timwi
@Timwi: Let's not use straw man arguments here. No one is suggesting to use the wrong tool for the job. Besides, my larger point here is that practices like brace usage improve readability and make it less likely that someone will introduce certain kinds of mistakes.
LBushkin
@LBushkin: Well, that’s subjective and I disagree with it. I think excessive braces make the code much harder to read. (I am also surprised that this question isn’t already closed for being subjective and argumentative.)
Timwi
+4  A: 

Your second version is "best practice". ReSharper will complain about the empty code block, and it's generally better to use fewer keywords than more. Yes, version two takes up more whitespace, but that's not necessarily a bad thing, and it has fewer non-whitespace chars.

KeithS
+6  A: 

Does the empty else make your code more readable? No, but the braces do.

JDT
+1  A: 

It took me a while to understand what everything belongs to in the first example, so I'd say it's bad practice.

Personally I

  1. Never ever nest braceless control structures because it can be very hard to read.
  2. Use braces on either both the if and else, or neither.

So I'd format it as follows:

if (lsvAddons.SelectedItems.Count > 0)
{
    foreach (ListViewItem A in lsvAddons.SelectedItems)
    {
        if (Addons[A.Index] != null) 
            Addons[A.Index].DoHelp();
    }
}
else
{
    Console.WriteLine(_GenericHelpString)
}
Matti Virkkunen
A: 

Readable means => best practice. Using bracers always saves the day, don't forget that.

Onatm
+2  A: 

Excessive braces are unnecessary and annoying.

I don’t mind braces, and I think if you have several levels of nesting, you should use them even if there is only one statement. But you shouldn’t religiously use them all the time.

For something very simple like

if (some_condition)
    Console.WriteLine("some info");

using braces would be completely over the top, and would make it much harder to see the bigger picture of the surrounding code (because you can fit less of it on the screen).

Timwi