[Issue 6579] Calling static method should *require* using type and not instance, unless specified by author

d-bugmail at puremagic.com d-bugmail at puremagic.com
Wed May 16 14:55:01 UTC 2018


https://issues.dlang.org/show_bug.cgi?id=6579

--- Comment #10 from Steven Schveighoffer <schveiguy at yahoo.com> ---
This is a pretty old issue, and I'm not sure it's super-important.

But to answer your question, the idea would be for the type to opt-in on having
a static function be considered part of the instance by aliasing. If it didn't
do that, then the function wouldn't be part of the instance, so you would have
to use typeof. It's a choice the type designer should make.

This does solve a problem for functions that are static and named in a way that
confuses what they do. It opens up a way to have functions that use the type to
clarify what the function is doing.

The example I brought up earlier, imagine you have a Stream type, and you have
a static function "open(char [] name)" that creates a new stream. This can
cause confusion:

Stream s;

s.open("foo.txt"); // creates a new stream and returns it, then it goes out of
scope immediately

assert(s.isOpen); // fails!

However, when used properly, it reads correctly:

auto s = Stream.open("foo.txt");

assert(s.isOpen);

I can rename the function something else, e.g. "createNewFile" or something,
which doesn't look correct on an instance, but if the language can require
using the type name, then it's easier to design.

Basically, it gives more power to the type designer on how his API looks.

Given that there are numerous workarounds, including factory functions outside
the type, and UFCS, I'm not sure how much this enhancement is still relevant.
It just means anyone adding static functions to a type has to consider how it
looks being run on an instance, and likely choose something outside the type
instead.

--


More information about the Digitalmars-d-bugs mailing list