Method overloading and code duplication promotion

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

The methods themselves can go in a base class that will make a particular class cleaner, but then the base class will have a problem (working on the problem). The params keyword seems like a solution, but I can imagine if I really think about this idea (using parameters, not separate parameters), there will be some other problem.

So, am I the only one who thinks that overloads contribute to code duplication?

thank

+3
source share
4 answers

Normally, I would have the actual implementation in an overload with most of the parameters, and other overloads would cause this default transfer for parameters that are not set.

Of course, I will not duplicate the code that writes the file to different overloads - in fact, this code can perhaps be reorganized into its own private parameterized private method.

+10
source

In addition to the options above, the upcoming default C # version feature, which is basically just syntactic sugar for what Winston suggested.

public string WriteToFile(string file, bool overWrite = false){
}
+2
source

, , , :

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

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

, .

+1

If all overloads use the same code, they simply process it a little differently, perhaps you need to either make another function that calls each overload, or if one of them is the basic, common version, then each of the other overloads should call common.

+1
source

Source: https://habr.com/ru/post/1732039/


All Articles