Friday, January 23, 2009

Consistency in APIs

One thing that I feel is very important when building APIs is consistency in how method parameters are ordered. Abrams and Cwalina's Framework Design Guidelines talks about this as well.

I came across one instance of inconsistency that is a good example, I think. We're using MSTest for unit testing on our current project and so we make extensive use of it's "Assert" class. For most of the assertions that do a comparison between and expected and actual object, you pass the expected object first. For example:

Assert.AreEqual(Of T)(expected as T, actual as T)
or
Assert.AreSame(expected as Object, actual as Object)

And now we come to the exception.


Assert.IsInstanceOfType(value as Object, expectedType as System.Type)

When using the assertion for IsInstanceOfType, suddenly it takes the actual object in the first position. This becomes annoying because now I have to remember if I put the actual or expected object first every time I use an assertion method.



Additionally, they've also named the expected object parameter "value" instead of "expected".


So, when building APIs even if you are not planning on publishing them for devs outside of your project, remember to be consistent with parameter ordering and naming. It helps with discovery and adoption of the API.

1 comment:

Euan Garden said...

I saw your comment on Rico's blog, about MSTEST perf.

Can you try a quick fix for me. In 2008 go into Tools |Options|Test Tools|Test Project and then make sure disable background discovery… is checked, now go into Test View and use it.