What to do when you want to add attributes to your class functions?

Adam D Ruppe destructionator at gmail.com
Fri Sep 16 12:42:40 UTC 2022


On Friday, 16 September 2022 at 09:25:58 UTC, RazvanN wrote:
> However, now you are faced with a large breaking change because 
> suddenly you force your users to respect these attributes. This 
> seems like a severe limitation to me.

It is *absolutely* necessary to maintain the integrity of 
interfaces.

see 
http://dpldocs.info/this-week-in-d/Blog.Posted_2022_07_11.html#run-time-dispatch for some tangentially related discussion

> The override is not even marked as @safe and the compiler does 
> not indicate that the function is @safe because it overrides a 
> safe function.

The error message could perhaps point it out, but this behavior 
is also quite useful, letting implementations usually just work.


> The point is, there is no way for a library owner to satisfy 
> both people that want attributes and people that don't.

You could have two branches of the interface. It is always 
allowed to add restrictions to child classes, so you could have

class Base { void foo(); }
class StrictBase : Base { void foo() @nogc pure etc; }

then people use those. Or, you can have

class Base {
    int foo_strict() @nogc pure etc {}
    final void foo() { }
}

Though that gets weird if you wanted to override the other one i 
still use final on purpose here cuz that's less weird than having 
both and needing to choose one.

> It just seems simpler to never use attributes at all (with 
> classes).

Or never use the attributes at all with anything. They don't 
actually provide much value anyway.

> However, now, if we mark the methods as @nogc we break 
> downstream code (phobos as well) because suddenly those methods 
> need to abide to new restrictions.

In this case, either the overload or an outright breaking change 
is the right thing to do. I find it very unlikely these are 
actually overridden often. But the possible breaking of error 
handling needs to be considered regardless of attributes.


More information about the Digitalmars-d mailing list