Usable API

time to read 5 min | 889 words

Here are a couple of suggestions when you design your API. They are mostly about dealing with passing collections:

  • "params" is your friend, it is much nicer to be able to write this:

    foo.WithArgs("Bar","Foo","Fubar");

    That to write this:

    foo.WithArgs( new string[] { "Bar", "Foo", "Fubar"} );

    The former is easier to read and to write.
  • One very important this to be aware of, try very hard not to write declarations like this one:

    void WithArgs(string username, string password, params string[] optional);

    It is very confusing to read afterward, and removing a single parameter may change the intention of the code.
  • When you need a method that takes several collection parameters, try to ensure that the most commonly used argument at the end, so it would be easier to extend:

    FindAll(Order[] orders, params ICriterion[] criterias)

    It is much easier to work with this method.
  • Finally, when you have code like the above, be sure to specify an overload that takes a single parameter of the first one, like this:

    public static T FindFirst(Order order, params ICriterion[] criterias)

    This saves you the need to define an array for the simple cases.