oop – Redundant code inside a method in java
oop – Redundant code inside a method in java
You want to clean your code. The below works. You can make errorMsg
global inside your class. You can create a custom Exception
for your needs.
public String myMethod() {
try {
doBunchOfStuff1();
doBunchOfStuff2();
doBunchOfStuff3();
} catch (Exception e) {
return e.getMessage();
}
return OK;
}
public void doBunchOfStuff1() throws Exception {
//
checkError(errorMsg,somethingElse);
}
public void doBunchOfStuff2() throws Exception {
//
checkError(errorMsg,somethingElse);
}
public void doBunchOfStuff3() throws Exception {
//
checkError(Error ,something else);
}
public void checkError(String errorMsg, String somethingElse) throws Exception {
if (errorMsg != null) {
throw new Exception(errorMsg + somethingElse);
}
}
}
First of all, I think its not a very good idea to return error message as a String (and null otherwise, is it correct?). Create a custom class called Result or something (which, probably, contains fields like boolean success and error message), or throw Exception
with some message.
Exceptions
behave like you described, but they not just return the caller method but fall through the entire call stack. You can use its feature and instead of repeating if (error = null)
constructions you can do nothing (let them fall further with the same error message and params), or handle one by one or all of them within a big try-catch
block, depending on design of your app.
oop – Redundant code inside a method in java
Over Engineered
abstract class Filter {
public static String errorMsg = null;
public abstract boolean check();
}
class CheckError extends Filter {
@Override
public boolean check() {
return (errorMsg != null);
}
}
abstract class DoBunchOfStuff {
public String somethingElse = null;
private static int counter = 0;
public DoBunchOfStuff() {
somethingElse = doBunch + ++counter;
}
public abstract void ofStuff(Filter filter);
}
class Follower {
private Filter filter;
private List<DoBunchOfStuff> stuff = new ArrayList<>();
public Follower(Filter filter) {
this.filter = filter;
}
public void add(DoBunchOfStuff bunchOf) {
stuff.add(bunchOf);
}
public String call() {
for (DoBunchOfStuff doBunch : stuff) {
doBunch.ofStuff(filter);
if (filter.check()) {
return filter.errorMsg + doBunch.somethingElse;
}
}
return OK;
}
}
public class YourClass {
public String myMethod() {
Follower executor = new Follower(new CheckError());
DoBunchOfStuff doBunch1 = new DoBunchOfStuff() {
@Override
public void ofStuff(Filter filter) {
//
}
};
DoBunchOfStuff doBunch2 = new DoBunchOfStuff() {
@Override
public void ofStuff(Filter filter) {
//
}
};
DoBunchOfStuff doBunch3 = new DoBunchOfStuff() {
@Override
public void ofStuff(Filter filter) {
//
filter.errorMsg = Error !!! ;
}
};
executor.add(doBunch1);
executor.add(doBunch2);
executor.add(doBunch3);
return executor.call();
}