Sean Thoman
Sean Thoman

Reputation: 7489

Member verification vs Interface

I was ready up on Ruby's method of enforcing interfaces w/ dynamic typing by checking for the existence of methods/properties that satisfy an interface.

In what ways is this overall just a better design principle than using interfaces? What are the pros/cons. For example you could implement the same concept in C# but I'm not sure if it would have the same value,

public class Foo
{
   public Foo(dynamic _obj)
   {
        MethodInfo[] methods= _obj.GetType().GetMethods();

        if (!methods.Any(x => x.Name == "SomeRequiredMethod")
        {
            throw new ArgumentException("Object does not meet interface requirements.");
        }
   }

   // proceed with functionality that requires the method
}

And of course you could extend this to check more than just the name, like the signature, return type, etc.

Thoughts?

Upvotes: 2

Views: 66

Answers (1)

Thomas Levesque
Thomas Levesque

Reputation: 292555

I can see several major issues problems with this approach:

  1. reflection is slow
  2. dynamic calls are also much slower than strongly-typed calls
  3. the code is more complicated

And I can't see any advantage, except perhaps for very specific needs...

C# was designed as a static, strongly-typed language, and even though it now has some dynamic capabilities, they should only be used when there is no strongly-typed alternative.

If you really need to use the object dynamically, don't check the members manually: instead, put the code in a try block, and catch the RuntimeBinderException that will occur if a member you call is missing.

Upvotes: 1

Related Questions