java想要一些建议来清理一系列if语句
我有一个方法,它做了大量的验证,它正在失控。如果您能就如何最好地清理这种方法提出建议,我将不胜感激。我使用的是Java11,这个方法是SpringBoot微服务的一部分
public void validateRequest(DepositRequest depositRequest, String transferId, String userId) {
if (!Arrays.asList("REALTIME_PAYMENT", "ACCOUNT_PAYMENT").contains(depositRequest.creditTransfer()
.getTransferInformation().getValue())) {
logError(depositRequest, participantUserId, etransferId, INVALID_ACCOUNT_NUMBER);
throw new ServerValidationException(INVALID_ACCOUNT_NUMBER, PAYMENT);
}
if (depositRequest.creditTransfer().getGroupHeader().getSettlementInformation().getClearingSystem() == null) {
logSchemaValidationError(depositRequest, etransferId, participantUserId, "proprietary");
throw new ServerValidationException(SCHEMA_VALIDATION_ERROR, PAYMENT);
}
if (depositRequest.creditTransfer().getGroupHeader().getInstructing()
.getInstitutionIdentification().getMemberIdentification() == null) {
logSchemaValidationError(depositRequest, etransferId, participantUserId, "member_identification");
throw new ServerValidationException(SCHEMA_VALIDATION_ERROR, PAYMENT);
}
if (depositRequest.creditTransfer().getGroupHeader().getInstructed()
cialInstitutionIdentification().getMemberIdentification() == null) {
logSchemaValidationError(depositRequest, etransferId, participantUserId, "member_identification");
throw new ServerValidationException(SCHEMA_VALIDATION_ERROR, PAYMENT);
}
if (depositRequest.creditTransfer().getTransferInformation().getCreditor().getName() == null) {
logSchemaValidationError(depositRequest, etransferId, participantUserId, "creditor.name");
throw new ServerValidationException(SCHEMA_VALIDATION_ERROR, PAYMENT);
}
if (depositRequest.creditTransfer().getTransferInformation().getDebtor().getName() == null) {
logSchemaValidationError(depositRequest, etransferId, participantUserId, "debtor.name");
throw new ServerValidationException(SCHEMA_VALIDATION_ERROR, PAYMENT);
}
if (depositRequest.authorization() != null) {
if (depositRequest.authorization().getToken() == null ||
authorization().getToken().length() < 1 ||
authorization().getToken().length() > 35) {
logSchemaValidationError(depositRequest, etransferId, participantUserId, "participant_authorization_token");
throw new ServerValidationException(SCHEMA_VALIDATION_ERROR, PAYMENT);
}
}
if (!isCreditorAccountIdentificationValid(depositRequest.creditTransfer().getTransferInformation().getIdentification())) {
logSchemaValidationError(depositRequest, etransferId, participantUserId, "identification");
throw new ServerValidationException(INVALID_ACCOUNT_INFO, PAYMENT);
}
if (!depositRequest.creditTransfer().getTransferInformation().getSettlementDate().equals(LocalDate.now())) {
logSchemaValidationError(depositRequest, etransferId, participantUserId, "settlement_date");
throw new ServerValidationException(SCHEMA_VALIDATION_ERROR, PAYMENT);
}
}
# 1 楼答案
简单的代码就是好代码。您当前的代码易于理解和维护。所以我不必急于改变它。但如果你愿意,你可以:
在单独的私有方法中执行每个验证,只需调用主验证方法中的每个方法
您可以想象并创建一个验证程序接口
然后,为每个验证创建此接口的实例,并将它们放在列表中,以便验证成为