tags:

views:

63

answers:

4

Hi,

Overloaded methods tend to encourage a habit of duplicating the code between all methods of the method group. For example, I may concat a string, write it to file, etc in one method but then do the same in another method but with the addition of an additional parameter (Creating the overload).

The methods themselves could go in a base class which will make the concrete class look cleaner but the base class will have the problem then (working around the problem). The params keyword seems like a solution but I can imagine if I really think this idea through (using params rather than individual parameters), there'll be some sort of other issue.

Am I therefore the only one to think that overloads promote code duplication?

Thanks

+9  A: 

Usually I'd have the actual implementation in the overload with the most parameters, and have the other overloads call this one passing defaults for the parameters which aren't set.

I certainly wouldn't be duplicating code which writes to a file across different overloads - in fact, that code alone could probably be refactored out into its own properly parameterized private method.

Winston Smith
I was writing the same post then saw yours. Any language feature can lead to code bloat.
rerun
I think everyone came up with just about the same answer here... just different ways of saying it, but I think Winston put it the best :)
Jrud
+1  A: 

A common pattern that more or less eliminates this problem is to have one base implementation, and have each overload call the base implementation, like so:

string WriteToFile(string fileName, bool overwrite) {
   // implementation
}

string WriteToFile(string fileName) {
   WriteToFile(fileName, false);
}

This way there is only one implementation.

Ryan Brunner
+1  A: 

If all of the overloads use the same code, they just handle it slightly differently, perhaps you should either make another function that each overload calls, or if one of them is a base, generic version, then each of the other overloads should call the generic one.

Jrud
+1  A: 

In addition to the options above, upcoming in the new version of c# is default parameter capabilities, which is basically just syntatic sugar for what Winston suggested.

public string WriteToFile(string file, bool overWrite = false){
}
jvenema