Duck typing and safety.

Adam Burton adz21c at googlemail.com
Fri Aug 13 10:19:24 PDT 2010


simendsjo wrote:

> While reading std.range, I though that a ducktyping design without
> language/library support can be quite fragile.
> 
> Consider the following example:
> 
> import std.stdio;
> 
> struct S
> {
> void shittyNameThatProbablyGetsRefactored() { };
> }
> 
> void process(T)(T s)
> {
> static if( __traits(hasMember, T, "shittyNameThatProbablyGetsRefactored"))
> {
> writeln("normal processing");
> }
> else
> {
> writeln("Start nuclear war!");
> }
> }
> 
> 
> void main()
> {
> S s;
> process(s);
> }
> 
> 
> If you rename S's method, process() does something completely different
> without a compile time error. By using interfaces this is avoided as the
> rename would break the interface.
> 
> Is there any idoms you can use to avoid stuff like this? Relying on
> documentation doesn't seem like a good solution.
Put "static assert(0)" in the else condition for D1 or D2, or in D2 you 
can use constraints which I think would look something like this (not used 
D2 much at all yet so this is a guess).

void process(T)(T s)
    if( __traits(hasMember, T, "shittyNameThatProbablyGetsRefactored"))
{
    writeln("normal processing");
}


More information about the Digitalmars-d-learn mailing list