@safe by default

Jonathan M Davis newsgroup.d at jmdavisprog.com
Sat Jun 16 21:33:55 UTC 2018


On Saturday, June 16, 2018 21:08:27 Jacob Shtokolov via Digitalmars-d wrote:
> On Saturday, 16 June 2018 at 17:46:56 UTC, Jonathan M Davis wrote:
> > doing that with attributes is rather error-prone, because it's
> > easy for folks reading the code to miss them, making it unclear
> > that they're in effect, and because unfortunately most
> > attributes cannot be reversed, mass-applying them like that can
> > then cause problems down the line when you need the attribute
> > to _not_ apply to a function.
>
> I completely agree with the second point - if we can't reverse
> these attributes in random places, the feature doesn't make sense
> at all.
>
> The first point, however, looks arguable to me. So I would say
> that it strongly depends on the task: for example, in web
> development there is absolutely no need to use pointers and other
> unsafe features until you really need them. In this case it's
> better to force safety for all functions by default, and it would
> be hard to do if we need to mark every single function as @safe
> (not that hard of course, but very unpleasant).

The problem isn't whether changing the default is desirable. It's the fact
that it's not at all obvious to anyone reading the code that that's what's
happening - especially when you're dealing with stuff like github pull
requests, where you're looking at a diff of the code and don't see the top
of the file as part of the diff. This problem has popped up several times in
druntime and Phobos where an attribute was mass-applied to a module or a
struct, and it's caused varying levels of problems. Sometimes, it just means
that an attribute ends up being applied locally in addition to being
mass-applied, but in other cases, it's resulted in folks outright
misunderstanding an aspect of the code that relates to the attribute that
was mass-applied.

Personally, I think that it's just plain bad practice to mass-apply
attributes precisely because it causes confusion about the code. And I'd say
the same even if all attributes were reversible. Being able to do something
like pure(false) would definitely be useful with mass-applied attributes,
but it wouldn't fix the maintenance problems that come from applying
attributes in a completely different part of the file from the function
being affected.

So, while you're certainly free to mass-apply @safe (or any other attribute)
if you think that that will improve your code, I'd advise against it.

- Jonathan M Davis



More information about the Digitalmars-d mailing list