Scope guards style guide
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Mon Mar 31 02:11:39 UTC 2025
On Sunday, March 30, 2025 3:47:22 PM MDT Elias Batek (0xEAB) via Digitalmars-d wrote:
> *The D Style*[0] doesn’t specify how scope guards should be
> written AFAICT.
>
> ```
> scope(exit) action;
>
> scope (exit) action;
>
> scope(exit)
> action;
>
> scope (exit)
> action;
> ```
>
>
> Currently, Phobos mixes all variants.
>
> - `scope\(exit\).+\n`: 316 matches in 42 files
> - `scope \(exit\).+\n`: 14 matches in 6 files
> - `scope\(exit\)\n`: 38 matches in 12 files
> - `scope \(exit\)\n`: 11 matches in 6 files
>
> (Numbers might be slightly different for `~master`.)
>
> **Is there any official recommendation on which style to use in
> which situation?**
>
> The first variant seems to be preferred in practice.
> Nevertheless, it differs from `version (…)` statements that have
> a space in between.
>
> [0] https://dlang.org/dstyle.html
Well with regards to
scope(exit)
action;
vs
scope(exit) action;
that's pretty much the same as
if (cond)
action;
vs
if (cond) action;
and we don't say anything about that in the style guide either. I expect
that putting it on the next line is more common with if statements, but
there probably are some cases where it goes on the same line. Either way, we
clearly haven't felt the need to get picky about it with if, so I don't know
that it's worth getting picky about it with scope.
As for scope(exit) vs scope (exit), in most places, the guide wants a space
between the keyword and the parens, but for assert, it doesn't. So, I guess
that it's a question of whether it's more like assert or more like other
keywords. Honestly, the logic of it never made sense to me. I don't put
spaces between keywords and parens in my own code, and I see no value in it,
but Andrei wanted to have the spaces because they weren't functions.
Personally, I fail to see why that matters, but clearly it does with how he
thinks about things. And that's why the style guide is the way that it is.
scope(exit) could arguably viewed as a single keyword, since it kind of is
in term of how it's used, but it isn't actually. It could also be viewed as
needing a space simply because we require that for keywords in general. But
I don't know why assert is different. Maybe Andrei thinks of it more like a
function, and scope(exit) certainly doesn't fit that thought process.
Personally, I'd favor not having the space, just because I think that all of
those spaces are unnecessary cruft, but we require them all over the place
for other stuff. So, I don't know. Probably the most consistent thing would
be to require the space simply because it's required for all of the other
keywords except assert.
- Jonathan M Davis
More information about the Digitalmars-d
mailing list