Given two methods that are somehow duplicate logic:
default void method_one(int a, int b) {
LOGGER.info("abc");
final long start = System.currentTimeMillis();
doMethod_A(a, b);
final long end = System.currentTimeMillis();
LOGGER.info(String.format("[abc] yep in %.2f sec", (end - start) / 1000f));
}
default void method_two(int c) {
LOGGER.info("xyz");
final long start = System.currentTimeMillis();
doMethod_B(c);
final long end = System.currentTimeMillis();
LOGGER.info(String.format("[xyz] yep in %.2f sec", (end - start) / 1000f));
}
I am thinking about how to avoid duplicate logic... any ideas?
CodePudding user response:
public void method_one(int a, int b) {
doWithTimeCheck("abc", () -> doMethod_A(a, b));
}
public void method_two(int c) {
doWithTimeCheck("xyz", () -> doMethod_B(c));
}
private static void doWithTimeCheck(String name, Runnable task) {
LOGGER.info(name);
long start = System.currentTimeMillis();
task.run();
long end = System.currentTimeMillis();
LOGGER.info(String.format("[%s] yep in %.2f sec", name, (end - start) / 1000.));
}
private void doMethod_A(int a, int b) {
System.out.println("doMethod_A");
}
private void doMethod_B(int c) {
System.out.println("doMethod_B");
}