Method signatures

With a few simple tricks, you can avoid those annoying changes in the method signatures in your application.

Method signatures are important point of integration in your application, and hence changes in your method signatures can be both annoying and error prone, and even break applications that consumes your code. So method signatures should be as stable and decoupled from the method implementation as possible. This can be done by e.g. defining interfaces, but I’ve learned that a few simple tricks can often make a huge difference.

A methods signature is its fingerprint: It’s name, parameters and return type. I am working on an application, where I search out segments of customers in a database based on different segmentation options, e.g. zipcode, gender and last name. The method is called SearchCustomers. The gender is a enumerations called Gender, whereas the the zipcode and last name are strings. I return a generic collection of customers from the method. So my methods signature is basically:

public List SearchCustomer(string zipcode, Gender gender, string lastName)

Now the name of this method is not likely to change, but the parameters are. Someday I will need to implement new segmention options like age, number of orders and so on. So oe way to avoid signature changes is by implementing a CostumerQuery object. The CustomerQuery is a simple container including the parameters, CostumerQuery.ZipCode, CustomerQuery.Gender and CustomerQuery.LastName. So before I do my search, I’ll simply populate an instance of my query object, and pass it to the search:

public List SearchCustomer(CustomerQuery customerQuery)

The benefit is, that when I need to add new search parameters, I’ll simply add them to the query object, and specify som default value. This will prevent code from breaking, even code written for the old method.

Another way to decouple the method is by returning my collection of customers as a IList. The IList is a generic interface available from .NET 2.0, implemented by the List object. It represents a collection of objects, that can be individually accessed by index, and supports the operations that I need to perform on the returned customers. So instead of binding my application to Microsoft specific implementation of the IList interface, I return my list as a interface instead. Note that the actual collection returned is still a List – it is simply returned as the less specific interface IList.

public IList SearchCustomer(CustomerQuery customerQuery)

Now, I’ll admit that not everybody will choose to return interfaces instead of the actual type, but the option exists. And to be hornest – In case mentioned above, it was not plausible that the returned type would ever change, so mainly due to lazyness I just returned the darn List.