Java: Using Lambda expressions to simplify code example: lambda expressions
Previously, the 3rd-party service was called, and every method was almost "long". It was too cool to write, and it was easy to modify and leak.
public void authorizeRoleToUser(Long userId, List<Long> roleIds) { try { power.authorizeRoleToUser(userId, roleIds); } catch (MotanCustomException ex) { if (ex.getCode().equals(MSUserException.notLogin().getCode())) throw UserException.notLogin(); if (ex.getCode().equals(MSPowerException.haveNoPower().getCode())) throw PowerException.haveNoPower(); throw ex; } catch (MotanServiceException ex) { CatHelper.logEventService("Power-authorizeRoleToUser", "authorizeRoleToUser", ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (MotanAbstractException ex) { CatHelper.logEventService("Power-authorizeRoleToUser", "authorizeRoleToUser", ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (Exception ex) { CatHelper.logError(ex); throw ex; }}
After learning and extracting encapsulation, I extracted try... catch... to the public and obtained these two methods:
import java.util.function.Supplier;public static <T> T tryCatch(Supplier<T> supplier, String serviceName, String methodName) { try { return supplier.get(); } catch (MotanCustomException ex) { if (ex.getCode().equals(MSUserException.notLogin().getCode())) throw UserException.notLogin(); if (ex.getCode().equals(MSPowerException.haveNoPower().getCode())) throw PowerException.haveNoPower(); throw ex; } catch (MotanServiceException ex) { CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (MotanAbstractException ex) { CatHelper.logEventService(serviceName + "-" + methodName, methodName, ex.getStatus(), ex.getErrorCode(), ex.getMessage()); throw ex; } catch (Exception ex) { CatHelper.logError(ex); throw ex; }}public static void tryCatch(Runnable runnable, String serviceName, String methodName) { tryCatch(() -> { runnable.run(); return null; }, serviceName, methodName);}
It is so simple to use now. For example:
public void authorizeRoleToUser(Long userId, List<Long> roleIds) { tryCatch(() -> { power.authorizeRoleToUser(userId, roleIds); }, "Power", "authorizeRoleToUser");}
There is also a returned value:
public List<RoleDTO> listRoleByUser(Long userId) { return tryCatch(() -> power.listRoleByUser(userId), "Power", "listRoleByUser");}
This is my first Java article. There are both surprises and disappointments in learning Java. We will continue to share our experiences in the future.