Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method overloads and code duplication promotion

Tags:

c#

oop

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

like image 477
theDeveloper Avatar asked Feb 09 '10 14:02

theDeveloper


People also ask

What is method overloading explain with an example?

In Java, two or more methods may have the same name if they differ in parameters (different number of parameters, different types of parameters, or both). These methods are called overloaded methods and this feature is called method overloading. For example: void func() { ... } void func(int a) { ... }

What is meant by method overloading?

Method overloading allows a class to define multiple methods with the same name, but different signatures. That is, it allows you to define different methods that have the same name, but that respond to correspondingly different messages sent to an instance of the class.

What is the benefit of having overloaded methods?

Advantages of method overloading in java Method overloading increases the readability of the program. Overloaded methods give programmers the flexibility to call a similar method for different types of data. Overloading is also used on constructors to create new objects given different amounts of data.

What is method overloading in oops?

Method overloading is a form of polymorphism in OOP. Polymorphism allows objects or methods to act in different ways, according to the means in which they are used. One such manner in which the methods behave according to their argument types and number of arguments is method overloading.


1 Answers

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.

like image 71
Winston Smith Avatar answered Nov 14 '22 23:11

Winston Smith