如何避免重复逻辑?
How to avoid 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));
}
我正在考虑如何避免重复逻辑...有什么想法吗?
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");
}
给定两种逻辑重复的方法:
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));
}
我正在考虑如何避免重复逻辑...有什么想法吗?
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");
}