Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add new exception in existing method without affecting legacy code

Tags:

java

exception

I was asked this question in an interview.

I have a method say public int add(int i, int j) and this method is already being used by many clients.

Now i have to make an update (may be some enhancement) to the add method which creates a scenario where i have to throw an exception. How can i make the existing clients to continue use the add() method without code change from their end? [Interviewer gave a hint: Clients may or may not use whatever new enhancement I made in add method]

First, I thought of overloading add, wrapping add in a new add method which throws exception. Then i thought of throwing Exception as RuntimException from add...

But none of them accepted as a correct approach.

Any pattern or design approach i am missing?

like image 981
Anonymous Avatar asked Nov 01 '12 07:11

Anonymous


People also ask

What is refactoring legacy code?

Refactoring legacy code is the process of improving the structure of an old or unfamiliar code without changing its functionality. The idea is to clean up lines of complex codes so you can understand or work with them better. This may include reducing redundancies or errors to make the code readable and manageable.

What is a legacy code give an example?

Legacy code is old computer source code. It could simply refer to an organization's existing code base which has been written over many years, or it could imply a codebase that is in some respect obsolete or supporting something obsolete.


1 Answers

Approach 1: Make use of Wrapper Class Integer

public class B {
    public int add(int i, int j) {
        return 0;
    }

    public int add(Integer i, Integer j) throws Exception {
        return 0;
    }
}

Approach 2: Make use of Overriding

You can take the advantage of overriding method can choose not to throw exception at all.

What you can do is to declare a Parent class which will have method with exception and child class which does not have the exception and will override method from parent. Now, when you want clients to use add with exception pass reference with type A, otherwise pass reference with type B:

class A { // <---New Class
    public int add(int i, int j) throws Exception { // <-- Method with Exception
        return 0;
    }
}

class B extends A { // <----Original Class
    @Override
    public int add(int i, int j) { // <--- Original Method
        return 0;
    }
}
like image 142
Amit Deshpande Avatar answered Oct 15 '22 11:10

Amit Deshpande