Hi all.
I have several times encountered this problem, but now I want to get to the bottom of it. Basically, if you have two methods that looks almost completely the same, aside from maybe one line, what is the best way to refactor it into one method? I know that you can use OOP, which is what I tend to do. Let me explain with an example of my problem.
In my current project I encountered a situation where it would just feel like overkill. I had a method that I needed to change one line in while still having the option to use the old code. But since I hate to duplicate code. So instead of creating two almost identical methods I used an interface. The method would then take a parameter with an object that implemented that interface. That object would then be used on the line to do the part I needed to change yet keep. It looks like this:
The line with the comment is the one I am talking about. Anyway, the thing is that this method is only used by one other method. And the interface is only used by this method. So it feels a bit overkill to use this solution, but I didnt know what the best way to solve this would be. Is this the proper way to do it? Or is there a better one?private String getResult(Indexer i) { String result = data; int index = i.find(data); // THIS IS THE INTERESTING LINE if (index > -1) { result = data.substring(0, index); data = data.substring(index); hasMore = !data.isEmpty(); } else { hasMore = false; } return result.trim(); }
What is the best way to avoid duplicating code in cases like this?
Take care,
Kerr