This question already has an answer here:
- Single statement if block - braces or no? 17 answers
Recently I've been messing around with this. Note that I'm not using LINQ because while this could be easily be done that way, I could do this in any language.
Allow me to exemplify:
foreach ( var i in items )
{
if ( condition )
{
...
}
}
This could be read as: "for each item that meets condition
, do ...
"
Let's just say that ...
is several lines long. In order for me to know that that this code is equivalent to the statement above, I have to ensure that there is nothing after said if. I'd rather write it this way:
foreach ( var i in items )
if ( condition )
{
...
}
That said, since this particular case is rather brief, I could also write it this way:
foreach ( var i in items ) if ( condition )
{
...
}
And let's just say ...
is a single, short statement. This could all fit into a single line without looking jarring at all.
var x = new List<Foo>()
foreach ( var i in items ) if ( condition ) x.Add(i);
Which, in LINQ, would be:
x = items.Where( i => condition );
Remarkably similar.
Another interesting example, would be when I'm nesting foreach loops to look for something.
foreach ( var i in foos ) foreach ( var j in i.bars )
{
//Do Stuff With Bars
...
}
Contextually, the first foreach is tied to the second. What I'm actually interested in are the bars, not the foos. I think writing it this way reinforces that idea.
This is, essentially, the same thing we do when we chain if blocks, which should technically look like this:
if ( a )
{
...
}
else
{
if ( b )
{
...
}
}
Whereas, everyone I know, myself included, writes:
if ( a )
{
...
}
else if ( b )
{
...
}
I am not trying to take shortcuts or write less lines, but simply group things together because it makes sense for them to be together on the same line.