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?
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.
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.
public class B {
public int add(int i, int j) {
return 0;
}
public int add(Integer i, Integer j) throws Exception {
return 0;
}
}
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;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With