Reputation: 2708
I've got public method1(...) in some not-final class, which widely used in our project.
But I need to add some if-condition in to internal last private method of this class and do not break other business logic, implemented previously: (we got nested methods)
public static method1(...) {
method2(...)
}
private static method2(...) {
method3(...)
}
private static method3(...) {
method4(...)
}
private static method4(...) {
// here I want to add some if-condition
}
Should I overload all methods in order to introduce some boolean flag through parameters list for switching to my special condition in some situations OR I can make a private field in the class and just put it to my private metod4(...){...}
? Does in last way I get smelly code ?
Thanks a lot.
Upvotes: 0
Views: 60
Reputation: 109593
Having many connected static methods (with plural parameters passed around) is non-optimal for maintenance.
The first naive measure would be to introduce a class for the parameter lists (every parameter becomes a field). Then the parameter class might be extended without the methods changing.
Better consider whether static methods may become normal methods, and the class partly statefull.
public class C {
protected final A a;
protected final B b;
protected X x;
public C(A a, B b) { }
public void setX(X x) { }
public void method1() {
method2();
}
...
Or combine them.
One method calling the other in succession with the same parameters looks needing an Object Oriented rewrite.
Upvotes: 0
Reputation: 6950
I don't know what is your Project architecture and how much refactoring is acceptable, but my first idea was for State design pattern, because is a good choice when your object alter its behavior and its internal state changes. The object will appear to change its class.
But here actually is more about encapsulation. Since all you methods (M2,M3,M4) are private there is no need to worry about
not break other business logic implemented previously: (we got nested methods)
simply because they are not exposed to others. So as bottom-line - the changes are most likely to be proper if affect the public M1. Please note that chaining here is crucial in order to preserve the processing of the final result. The behavior of the method4 should be changed obviously. So the overloading of the private methods is a good option, if your suggested
private field in the class
is calculated in the invocation tree and not passed as param somehow.
Maybe if you post some more info or code - the answers will be more helpful.
Upvotes: 2