D UFCS anti-pattern

Andrej Mitrovic via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 25 00:52:09 PDT 2014


On 4/25/14, Steven Schveighoffer via Digitalmars-d
<digitalmars-d at puremagic.com> wrote:
> Recently, I observed a conversation happening on the github pull request
> system.

Another case of hijacking is the std.conv.text function. I've seen two
people so far that have accidentally called the global text function
by mistake, e.g.:

-----
import std.conv;
import std.stdio;

class C
{
    this(string user, string text) { _user = user; _text = text; }
    string _user;
    string _text;
}

void main()
{
    auto c = new C("John", "this is my message");
    string input = c.text;
    writeln(input);  // test.C, oops!
}
-----

UFCS has its benefits but it also has its drawbacks. And yet I
wouldn't want to ban the above code, but maybe we could figure out
some system for protecting against UFCS calls in some contexts. The
way I worked around the common `.text` pattern was to define a
@disable'd field in the class, which would override the global text
function and trigger a compilation error.


More information about the Digitalmars-d mailing list