Reputation: 2311
In VSCode, when writing javascript/typescript I often write ifs without curly braces. Especially for early exits.
foo() {
...
if(...)
return;
...
for(...) {
...
if(...)
continue;
...
}
...
}
In VSCode, the return/continue/whatever I put on the new line does not get indented. Is there any setting for this?
I only have icons and Debugger for Chrome extensions.
This is the way VSCode formats it:
It actually turns out this is not the only weird indentation going on!
This looks ok:
However, if I put the args on different lines. (may be required for long variable names):
The rest of that function ends up indented, and so does the rest of the file.
I've tried to reinstall VSCode, does not help.
Any suggestions?
Upvotes: 8
Views: 1410
Reputation: 28870
This won't answer your question about how to get VS Code to do what you want, but if I may offer some advice: leaving out the curly braces can be dangerous. It led to a major security flaw in Apple's implementation of SSL: the infamous goto fail bug.
Here's the code where they ran into trouble:
if ((err = SSLFreeBuffer(&hashCtx)) != 0)
goto fail;
if ((err = ReadyHash(&SSLHashSHA1, &hashCtx)) != 0)
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &clientRandom)) != 0)
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &serverRandom)) != 0)
goto fail;
if ((err = SSLHashSHA1.update(&hashCtx, &signedParams)) != 0)
goto fail;
goto fail;
if ((err = SSLHashSHA1.final(&hashCtx, &hashOut)) != 0)
goto fail;
See the problem?
Curly braces are not a perfect protection against bugs like this, but they certainly help. You're much less likely to have your own goto fail
bug when you use them.
Some developers, myself included, feel that it's OK to omit the curly braces only when you write the if
statement as a one-liner. If you're simply doing an early exit from a function, this is fine:
if( ... ) return;
You're much less likely to create a goto fail
bug when it's on a single line. But the moment you split it into two lines, the curly braces are required:
if( ... ) {
return;
}
or:
if( ... ) {
console.log( 'debug message' );
return;
}
Let's try that without the curly braces. First we have:
if( ... )
return;
No worries, this code works as expected. Now let's add the debug message:
if( ... )
console.log( 'debug message' );
return;
Oops!
Since you're putting the open curly brace on the same line as the if
statement already (which I completely agree with), it only costs you one extra line to add the closing curly brace. Either make your early returns one-liners, or use the curly braces. This will avoid the risk of an eventual goto fail
bug of your own.
Upvotes: 3