Duck typing and safety.
Ryan W Sims
rwsims at gmail.com
Fri Aug 13 10:20:32 PDT 2010
On 8/13/10 10:01 AM, 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.
If what you want is compile-time type safety, then duck typing is
probably not for you. That's sort of the whole point behind duck typing:
you defer typing decisions to runtime. If you need compiler breakage for
something like that, use interfaces.
--
rwsims
More information about the Digitalmars-d-learn
mailing list