What's better practice when defining several methods that return the same shape of data with different filters? Explicit method names or overloaded methods?
For example. If I have some Products and I'm pulling from a database
explicit way:
public List<Product> GetProduct(int productId) { // return a List }
public List<Product> GetProductByCategory(Category category) { // return a List }
public List<Product> GetProductByName(string Name ) { // return a List }
overloaded way:
public List<Product> GetProducts() { // return a List of all products }
public List<Product> GetProducts(Category category) { // return a List by Category }
public List<Product> GetProducts(string searchString ) { // return a List by search string }
I realize you may get into a problem with similar signatures, but if you're passing objects instead of base types (string, int, char, DateTime, etc) this will be less of an issue. So... is it a good idea to overload a method to reduce the number of methods you have and for clarity, or should each method that filters the data a different way have a different method name?
Yes you can overuse it, however here is another concept which could help keep the usage of it under control ...
If you are using .Net 3.5+ and need to apply multiple filters you are probably better to use IQueryable and chaining i.e.
That way you can reuse the filtering logic over and over whereever you need it.
I have seen overloading overused when you have only subtle differences in the arguments to the method. For example:
In my small example, it quickly becomes unclear if the second
int
argument should be the owner or customer id.You can use Overloading as much as you want. From the best practices point of view as well, it is recommended that you use Overloading if you are trying to perform the same "operation" (holistically) on the data. E.g. getProduct()
Also, if you see Java API, Overloading is everywhere. You wouldn't find a bigger endorsement than that.
yes you can overuse it. In your example it would seem like the first and third would probably return a single item, where the second would return several. If that is correct, then I would call the first and third GetProduct and the second GetProducts or GetProductList
if this is not the case and all three return several (as in if you pass it productID 5, it returns any items with 5 in the productid, or returns any items with the string parameter in its name) then I would call all three GetProducts or GetProductList and override all of them.
In any event, the name should reflect what the function does, so calling it GetProduct (singular) when it returns a list of Products doesn't make a good function name. IMNSHO