There’s only one right place for curly braces
- Written by June Blender
- Last Updated: 14 April 2016
- Created: 03 March 2016
- Hits: 958
If you ever want to start an argument with programmers or scripters, mention your preferred code or script formatting habit.
A tweet about the PowerShell backtick continuation character or the placement of comment-based help for a function will elicit enough reaction to bring down a small server.
But nothing gets people more riled up than the position of curly braces in a script block. On the same line or a separate line?
First, PowerShell MVP Aleksandar Nikolic will remind you (and rightly so!) that “curly braces” is redundant, because all braces are curly. That’s how you distinguish braces from brackets.
Then, everyone who’s not on deadline, and a few people who are, will weigh in about how their curly brace placement is the right way. It’s the professional way. It’s the clearest way. It’s the historic way. It’s the new way.
In general, PowerShell doesn’t care about white space or line breaks before curly braces in script blocks. They matter only in structures like hash tables. But, everyone else cares.
Place open brace on new line (or not!)
PowerShell Studio wouldn’t dare to make the critical choice of curly brace placement for you. Instead, you decide where you want your curly braces in script blocks.
To declare your choice:
- In PowerShell Studio, click Home and in the Windows group, click Options.
- Under Editor, click Formatting.
- Check or uncheck: Place open brace on a new line.
The script diagram shows you the effect.
On the same Formatting page, you can also set your Triggers, that is, the characters on which PowerShell Studio evaluates and reformats for you, if necessary.
As a result, when you hit a trigger or click the amazing Format Script button (Home/Edit), PowerShell Studio formats your script with the curly braces where you want them.
Remember that Place open brace on a new line affects only basic script blocks, like those in an IF statement. It doesn’t affect other instances of curly braces, like those in hash tables, functions, or even the script blocks in event handlers.
So, there’s only one right place for curly braces in a script block. It’s where you want them.