Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this seemingly unconnected block (after an if statement) work?

Tags:

c#

I've inherited some code that makes occasional use of the following if notation:

if (a)     foo(); {     if (b)         boo();     moo(); } 

I'm not sure how to read that naturally but the code compiles and runs.

Can someone please explain how this works so that I can rewrite it in more human readable format? Alternatively, could someone explain why this notation could be useful?

like image 272
Simon Avatar asked Aug 01 '17 22:08

Simon


Video Answer


1 Answers

The code you've posted would be better written as:

   if (a)    {        foo();    }    if (b)    {        boo();    }    moo(); 

Braces in C# have two purposes:

  1. They create a scope for variable declarations.
  2. They group statements together so that conditionals and loops and such can apply to several statements at a time.

Whoever wrote the code you've posted chose not to use them for the second purpose. if statements can be totally legitimate without using any braces, but they'll only apply to the statement that immediately follows them (like the call to foo() after the first if).

Because there is a legitimate use case for braces that has nothing to do with control flow, however, it is perfectly acceptable for someone to put braces in random places that have nothing to do with the if statements.

This code:

foo(); {    var a = boo(); } {    var a = moo(); } 

... is equivalent to this code:

foo(); var a = boo(); var b = moo(); 

... but you'll notice that I couldn't name the second variable a because it's no longer separated from the first variable by scoping braces.

Alternatively, could someone explain why this notation could be useful?

There are three possibilities I can think of:

  1. They wanted to reuse variable names in different parts of the method, so they created a new variable scope with the braces.
  2. They thought braces might be a nice visual aid to encapsulate all the logic that's found inside them.
  3. They were actually confused, and the program doesn't work the way they think it does.

The first two possibilities assume they're actually doing more than calling foo() and moo() in the real production code.

In any case, I don't think any of these possibilities are good reasons to write code like this, and you are totally within your rights to want to rewrite the code in a way that's easier to understand.

like image 75
StriplingWarrior Avatar answered Sep 19 '22 18:09

StriplingWarrior