D UFCS anti-pattern

Steven Schveighoffer via Digitalmars-d digitalmars-d at puremagic.com
Fri Apr 25 05:21:04 PDT 2014


On Fri, 25 Apr 2014 03:52:09 -0400, Andrej Mitrovic via Digitalmars-d  
<digitalmars-d at puremagic.com> wrote:

> 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.

I think this really comes down to a poorly named function. textOf, toText,  
textify even, are better names that wouldn't cause this problem.

-Steve


More information about the Digitalmars-d mailing list