Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding overuse of method overloading [closed]

I've come across a Java utility class that has four methods for processing data. All methods process and then write the parameters to the same file, and each method accepts four different sets of inputs:

util::process(String data1)
util::process(String data1, Object1 data2)
util::process(String data1, String data3)
util::process(String data1, Object2 data4)

I'm seeing what feels like a code smell because every time a new combination of data is introduced, a new method is also added. The method overloading feels like it is masking a design or object construction issue.

Is it possible to refactor this and avoid method overloading? How?

like image 515
TERACytE Avatar asked Dec 19 '25 22:12

TERACytE


2 Answers

This is an interesting question because there are not enough details to really say definitively. I do believe there is an odor coming off this code, and it's the stench of procedural trying to look like object-oriented programming. It's funny that the method is entitled 'process' and the types are either strings or generic object like names. What is doing the processing? Surely not a controller object, I am guessing. At some point, you want to have objects that have responsibilities. So let's assume that the base of this was the concept of an Application (e.g. an application for a job). You might want to pull the method process up into that type, and then use inheritance to augment functionality by introducing different Application types.

Another option would be to introduce a Chain of Responsibility pattern. The problem I see with that is you seem to be saying that there are only 2 links in the potential chain. The advantage of the chain approach is that the handlers don't have to know anything about each other.

A third option would be to make the successors implement an interface. This would be something like the Command Pattern, then the actual 'processing' is really just a trigger and each thing is responsible for its own behavior.

like image 76
Rob Avatar answered Dec 22 '25 11:12

Rob


IMHO it is not smelly because of overloading. If these weren't overloads, but different methods, it would be code smell anyway. From what you write, it seems that the code does not follow the open/closed principle. If don't provide more details on what you are trying to accomplish with the code, we cannot suggest any solution.

like image 39
Steves Avatar answered Dec 22 '25 10:12

Steves



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!