I ran across a piece of C# code today I had not seen before. The programmer defined a block of code using only curly braces (no if, class, function, etc).
{
int i = 0;
}
i++; //compile error
Is there a purpose to this other than making the code look more organized? Is it good, bad, or whatever practice to use this "floating" contexts?
You can use an open and close set of curly braces to define a self containing block, which has its own scope.
This is generally not considered good programming practice, though.
Usually if someone is doing something like this, it's probably better to create a method/function in its place.
Any variable inside the "scope" of these curly braces will be out of scope outside of it.
It limits the scope of the variable to within that block. So the variable i would not be able to be seen outside of those braces.
It can also be a preference on if someone wants to separate code but using this when not necessary would in most cases be superfluous.
The braces {} in C# define scope. Anything defined within them goes "out of scope" once the braces are terminated.
The example seems kind of pointless. I can't imagine why it would be used in real world code. I'm assuming you pared down the code presented?
There is no purpose to that code at all. Probably an artifact from something else he/she was trying to do. As the comment shows this won't even compile because i is out of scope.
From a coding style perspective I personally don't like it and I've never seen someone use floating braces to "organize" their code before.
The purpose of this is to illustrate that the int i is actually in a different scope than the incremented i below it.
Related
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?
The code you've posted would be better written as:
if (a)
{
foo();
}
if (b)
{
boo();
}
moo();
Braces in C# have two purposes:
They create a scope for variable declarations.
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:
They wanted to reuse variable names in different parts of the method, so they created a new variable scope with the braces.
They thought braces might be a nice visual aid to encapsulate all the logic that's found inside them.
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.
The curly brace starts after foo() instead of if(a) (like if(a){) therefore these braces are useless in this context.
if (a)
foo();
//{
if (b)
boo();
moo();
//}
which is equal to
if (a)
foo();
if (b)
boo();
moo();
Braces like those are used to limit context. Variables created inside these braces will exist only until the brace ends.
EDIT: I changed the Title to a more appropriate name, base on Comments from David
I am experienced with c# programming and have never really run into this before, though I am surprised I haven't
I am using Long name variables, because I plan to come back to my program in a few months from now, but I am annoyed at how long it is taking me to write code. I considered using shorter names then just replacing them all later. But I was wondering if there is syntax sugar for something like this
Using (var b as TheButtonThatMakesThingsHappen)
{
b.Name="TheButtonThatMakesThingsHappen";
b.Location=...
b.etc...
}
Instead of
TheButtongThatMakesThingsHappen.Name="TheButtonThatMakesThingsHappen";
TheButtongThatMakesThingsHappen.Location=...
TheButtongThatMakesThingsHappen.etc...
I did a google search and tried here on stackoverflow, but I don't know what this is called,
Any Ideas?
As David posted in the comments section on your question, I think that the method that you described for renaming is a needless shortcut to get around the issue of long variable names. Try to name the variables to something more constructive, like SubmitButton or UserSubmitButton instead of TheButtongThatMakesThingsHappen.There is something very wrong with your variable naming scheme... if you don't actually use it.
Another alternative to long variable names is comments with shorter, more descriptive variable names- for example:
button SubmitButton; //this button is used in the second form field of the website
I don't feel like there is an answer here yet. While I am starting to think the concept itself is flawed, at least for the reasons I want to do it, I think it is unfair not to have a proper solution for someone looking later. I have taking the suggestions From David and others and compiled this as my answer.
#region TheButtonThatMakesThingsHappen
{
var b = TheButtonThatMakesThingsHappen;
b.Name = "TheButtonThatMakesThingsHappen";
b.Location=...;
b.etc...;
}
#endregion
It allows a local scope alias and the region tags allow for collapsing code, which keeps things neater.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 11 years ago.
I mean other than using it when required for functions, classes, if, while, switch, try-catch.
I didn't know that it could be done like this until I saw this SO question.
In the above link, Eli mentioned that "They use it to fold up their code in logical sections that don't fall into a function, class, loop, etc. that would usually be folded up."
What other uses are there besides those mentioned?
Is it a good idea to use curly braces to limit the scope of your variables and expand the scope only if required (working on a "need-to-access" basis)? Or is it actually silly?
How about using scopes just so that you can use the same variable names in different scopes but in the same bigger scope? Or is it a better practise to reuse the same variable (if you want to use the same variable name) and save on deallocating and allocating (I think some compilers can optimise on this?)? Or is it better to use different variable names altogether?
I do if I am using a resource which I want to free at a specific time eg:
void myfunction()
{
{
// Open serial port
SerialPort port("COM1", 9600);
port.doTransfer(data);
} // Serial port gets closed here.
for(int i = 0; i < data.size(); i++)
doProcessData(data[i]);
etc...
}
I would not use curly braces for that purpose for a couple reasons.
If your particular function is big enough that you need to do various scoping tricks, perhaps break the function into smaller sub-functions.
Introducing braces for scoping to reuse variable names is only going to lead to confusion and trouble in code.
Just my 2 cents, but I have seen a lot of these types of things in other best practice materials.
C++:
Sometimes you need to introduce an extra brace level of scope to reuse variable names when it makes sense to do so:
switch (x) {
case 0:
int i = 0;
foo(i);
break;
case 1:
int i = 1;
bar(i);
break;
}
The code above doesn't compile. You need to make it:
switch (x) {
case 0:
{
int i = 0;
foo(i);
}
break;
case 1:
{
int i = 1;
bar(i);
}
break;
}
The most common "non-standard" use of scoping that I use regularly is to utilize a scoped mutex.
void MyClass::Somefun()
{
//do some stuff
{
// example imlementation that has a mutex passed into a lock object:
scopedMutex lockObject(m_mutex);
// protected code here
} // mutex is unlocked here
// more code here
}
This has many benefits, but the most important is that the lock will always be cleaned up, even if an exception is thrown in the protected code.
The most common use, as others have said, is to ensure that destructors run when you want them to. It's also handy for making platform-specific code a little clearer:
#if defined( UNIX )
if( some unix-specific condition )
#endif
{
// This code should always run on Windows but
// only if the above condition holds on unix
}
Code built for Windows doesn't see the if, only the braces. This is much clearer than:
#if defined( UNIX )
if( some unix-specific condition ) {
#endif
// This code should always run on Windows but
// only if the above condition holds on unix
#if defined( UNIX )
}
#endif
It can be a boon to code generators. Suppose you have an Embedded SQL (ESQL) compiler; it might want to convert an SQL statement into a block of code that needs local variables. By using a block, it can reuse fixed variable names over and over, rather than having to create all the variables with separate names. Granted, that's not too hard, but it is harder than necessary.
As others have said, this is fairly common in C++ due to the all-powerful RAII (resource acquisition is initialization) idiom/pattern.
For Java programmers (and maybe C#, I don't know) this will be a foreign concept because heap-based objects and GC kills RAII. IMHO, being able to put objects on the stack is the greatest single advantage of C++ over Java and makes well-written C++ code MUCH cleaner than well-written Java code.
I only use it when I need to release something by the means of RAII and even then only when it should be released as early as I possibly can (releasing a lock for example).
Programming in Java I have quite often wanted to limit scope within a method, but it never occurred to me to use a label. Since I uppercase my labels when using them as the target of a break, using a mixed case labeled block like you have suggested is just what I have wanted on these occasions.
Often the code blocks are too short to break out into a small method, and often the code in a framework method (like startup(), or shutdown()) and it's actually better to keep the code together in one method.
Personally I hate the plain floating/dangling braces (though that's because we are a strict banner style indent shop), and I hate the comment marker:
// yuk!
some code
{
scoped code
}
more code
// also yuk!
some code
/* do xyz */ {
scoped code
}
some more code
// this I like
some code
DoXyz: {
scoped code
}
some more code
We considered using "if(true) {" because the Java spec specifically says these will be optimized away in compilation (as will the entire content of an if(false) - it's a debugging feature), but I hated that in the few places I tried it.
So I think your idea is a good one, not at all silly. I always thought I was the only one who wanted to do this.
Yes, I use this technique because of RAII. I also use this technique in plain C since it brings the variables closer together. Of course, I should be thinking about breaking up the functions even more.
One thing I do that is probably stylistically controversial is put the opening curly brace on the line of the declaration or put a comment right on it. I want to decrease the amount of wasted vertical space. This is based on the Google C++ Style Guide recommendation..
/// c++ code
/// references to boost::test
BOOST_TEST_CASE( curly_brace )
{
// init
MyClass instance_to_test( "initial", TestCase::STUFF ); {
instance_to_test.permutate(42u);
instance_to_test.rotate_left_face();
instance_to_test.top_gun();
}
{ // test check
const uint8_t kEXP_FAP_BOOST = 240u;
BOOST_CHECK_EQUAL( instance_to_test.get_fap_boost(), kEXP_FAP_BOOST);
}
}
I agree with agartzke. If you feel that you need to segment larger logical code blocks for readability, you should consider refactoring to clean up busy and cluttered members.
It has its place, but I don't think that doing it so that $foo can be one variable here and a different variable there, within the same function or other (logical, rather than lexical) scope is a good idea. Even though the compiler may understand that perfectly, it seems too likely to make life difficult for humans trying to read the code.
The company I'm working at has a static analysis policy to keep local variable declarations near the beginning of a function. Many times, the usage is many lines after the first line of a function so I cannot see the declaration and the first reference at the same time on the screen. What I do to 'circumvent' the policy is to keep the declaration near the reference, but provide additional scope by using curly braces. It increases indentation though, and some may argue that it makes the code uglier.
This is my code:
if (RdoBtnBeepDefault.Checked) SystemSounds.Beep.Play();
else SoundPlayer iPlay = new SoundPlayer(#TxtBeepFile.Text);
iPlay.Play();
And here's the error:
Embedded statement cannot be a declaration or labeled statement
If that isn't possible, mind telling me how?
iPlay.Play(); is beyond the scope of your else clause in your if-else statement. Try enclosing it with braces for multiple line scope.
if (RdoBtnBeepDefault.Checked)
{
SystemSounds.Beep.Play();
)
else
{
SoundPlayer iPlay = new SoundPlayer(TxtBeepFile.Text);
iPlay.Play();
)
Not only that even this can produce the same error
if (RdoBtnBeepDefault.Checked) SystemSounds.Beep.Play();
else int i=0;
The reason is logic. If you put a single line statement in if else condition which indirectly means the conditional flow is ending with that line. In that case if you use some declaration||something as above which won't make sense/impact in any way, then that means It is kind of string literal. It is not exactly wrong, rather it is unneccessary. Mind c# visual studio editor reduces almost all the possible errors and unneccessary memory loading.
When you put braces, it indiactes that you may use that variable within the same block for some logic. So the editor will allow you to do that. At that time the VS assumes you may add the code in future. So it will give you only warning about that line. Without braces it is solidly assuming that you are not going to use that variable(due to scope).So, it takes that as error.
ReSharper usually suggests me that, and I'm still looking for a good reason of why to do that.
The only thing that came to my mind is that declaring it closer to the scope it will be used, can avoid initializing it in some cases where it isn't necessary (because a condition, etc.)
Something related with that is the following:
int temp;
foreach (var x in collection) {
temp = x.GetValue();
//Do something with temp
}
Is that really different than
foreach (var x in collection) {
int temp = x.GetValue();
//...
}
I mean, isn't the second code more expensive because it is allocating memory everytime? Or are both the same? Of course, after finished the loop, in the second code the garbage collector will take care about temp variable, but not in the first one...
Declaring as close as possible to use is a readability decision. Your example doesn't display it, but in longer methods it's hard to sift through the code to find the temp variable.
It's also a refactoring advantage. Declaring closer to source leads to easier refactoring later.
The cost of the second example is negligible. The only difference is that in the first example, temp will be available outside the scope of the for loop, and thus it will exist longer than if you declared it inside the for loop.
If you don't need temp outside the for loop, it shouldn't be declared outside that loop. Like others have said, readability and style are more at play here than performance and memory.
I agree that if you init a variable inside the scope that it's being used then you're helping the gc out, but I think the real reason is more to do with code maintenance best practices. It's sort of a way of reducing cognitive load on you or another developer coming back to the code after months (or years) of not looking at a particular block. Sure, IDE's help you discover things, but you still have to do the "go to definition" dance.
There is no performance benefits, I believe, but more of a coding style. Its more C programming style to declare it all at the beginning of the scope. There is more details here: Scope of variables in C#
Its a style personal preference thing to do with readability.
There are very few languages/systems where this will have any noticeable effect on performance.
I try to follow these two rules.
All the core attributes of a class should be defined together in one place. e.g. If you are handling an order then orderno, customerno, amount, sales tax etc. should be defined close together.
All the technical attributes which form part of the internal mechanics of the class such as iterators, flags, state varaibles should be defined close to thier usage.
Or to put it another business/external type data all defined in one place, technical/internal data defined close to usage.
The difference is a matter of coding style and one of such dispute that different coding standards have completely opposite rules. The conflict is still strongest in the C++ world where the C language forced variables to be declared at the beginning of a scope and so old-timers (like myself) were well accustomed to "looking at the beginning of the function" to find variables.
The C# style that you most often see is that variables come into existence right at the point where they are needed. This style limits the existence of the variable and minimizes the chance that you could mean some other variable accidentally. I find it very easy to read.
In the modern C# era, putting the declaration of variables at their first point of use is most clearly beneficial when combined with the both loved and hated var feature. Using var just isn't that useful unless you use it with an assignment that allows the compiler and readers to infer the type of the variable. The var feature encourages declaration with first use.
Me, I love var, and so you can guess which coding style I prefer!
I was always taught to declare your variables at the top of a function, class, etc. This makes it easier to read.