开发者

Method overloads and code duplication promotion

开发者 https://www.devze.com 2022-12-19 20:32 出处:网络
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 sa

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 th开发者_开发知识库e 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


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.


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){
}


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消