Thursday, August 11, 2011

Good API Design

I'm going through a few iterations of beginning to design an API. I came to a point in writing the operations where I stopped and thought about the parameter (and return types) I was using. The API is an interface for transferring a file. Originally I had two parameters.
void Upload(string fileName, string destinationUri);

I looked at this and thought...mmmmm...too many strings. Maybe I should specify a better type? But then string is nice and flexible right? What is the better approach? I came across a presentation from Joshua Bloch (a Principal Software Engineer from Google) who has a slide about exactly this.

The second and third point are key here
  • "Use most specific possible input parameter type"
Your user will have to construct the more specific type before using the API but as he says, the error then moves to compile time from runtime - this is much better.
  • "Don't use string if a better type exists"
In our case (.NET) there is a better type. The System.Uri type can replace the destinationUri string. In fact, you could argue that it could replace the filePath string too as file:// is a valid Uri.
void Upload(Uri from, Uri to);

That looks okay to me but I think I would prefer a string for the filePath. We don't really want users to pass in any other Uri except for ones beginning with "file://". Besides, the File API in .NET uses "string filePath" in several places so our API would be consistent with what users expect.

So I decided on this (notice I changed the 2nd parameter name to be more descriptive - I think this reads better).
void Upload(string filePath, Uri target);

This will probably change several times again - I like writing API's early and often and getting as much feedback as possible. Once they are released you can never change them only add to them! Or piss off a lot of your users by breaking backwards compatability! I'm looking at you Python.

No comments:

Post a Comment