C# and abusive dynamic APIs

I read a blogpost last night about dynamic code and how it could be used to handle arguments passed in to a method, and it got me thinking. I exchanged a couple of tweets with about this and I really didn’t get any wiser, hence I guess I have to go and try out some Ruby, but thats another day.

The thing I don’t get is how someone, in a public API designed for use by others, generally can think dynamic args or a collection of args can be received by a method which in turn just selects X of the passed in args without even bother looking at the rest of them? How are the consumer supposed to know what to name the keys/members to get their elements processed? If a method takes a collection of arguments, I as a consumer, kind of expect all the elements to be visited. I don’t wan’t to crank up Reflector and look at the source to see what I should name the keys and members to get them processed.

Lets start with an over exaggerated example using say a generic Dictionary.

public class AddressParser
    public string BuildAddress1(Dictionary<string, string> args)
        return string.Format("Street: {0}\r\nZip:{1} City: {2}\r\nCountry: {3}.",
            args["Street"], args["Zip"], args["City"], args["Country"]);

    public string BuildAddress2(dynamic args)
        return string.Format("Street: {0}\r\nZip:{1} City: {2}\r\nCountry: {3}.",
            args.Street, args.ZipCode, args.City, args.Country);

So, how would you as a consumer know that the args being processed are:”Street, ZipCode, City and Country”. Should you test all of the common names of address attributes? “StreetName, StreetNumber, Zip, Area….”

I asked:

And how would I now as a consumer that every element has been visited?

Because you’re an awesome tester and you don’t rely on your API method signatures to tell you what to do.

So pull up your sleeves and put on that monkey suite. It’s time to do some exploratory API programming.

To be fair, the dynamic example has one huge advantage. If I miss to pass something to the Dictionary method I get a not so informative KeyNotFoundException. If I instead use the dynamic example I get a more detailed exception:

'f__AnonymousType0' does not contain a definition for 'Country'

Ok, of course you could be a good citizen and document your method but we all know where that ends up.

I don’t know about you, but in this scenario, I don’t want to be forced to be a Curious George programmer.


About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s