如何减少多个if-else语句并减少代码的认知复杂性?

时间:2020-09-02 06:17:58

标签: java spring-boot

以下是用于创建交易日志然后执行交易的代码

 BankTransactions sourceBankTransaction = bankTransactionService.createBankTransaction(BankTransactionDto.builder()
                .amount(clientIbftRequest.getAmount() + chargeAmount)
                .bankTransactionEntry(bankTransactionEntry)
                .fromAccountNumber(clientSourceAccount)
                .toAccountNumber(clientDestinationAccount)
                .bank(sourceBankService.getBanks())
                .bankTransactionType(BankTransactionType.SOURCE)
                .transactionStatus(!clientService.isRequireSourceTransaction() ? TransactionStatus.NOT_REQUIRED :
                        TransactionStatus.PENDING)
                .statusCode(TransactionEntryRequestStatusKey.BANK_TXN_INITIATED.getCode())
                .statment(ConversionUtil.getStatement(TransactionNarrationConstant.BANK_TRANSFER))
                .build());

这些对象很多。它们都有不同的参数,例如transactionType,from和to帐户,银行。因此,在一次交易中,我有多个上述代码。这使我的方法很长。 而且,某些事务是同步执行的,而其他事务则需要不同的线程。有没有办法使它们动态化?

我试图用钥匙作为交易类型来创建地图

Map<String, List<BankTransactions>> = new HashMap();

,然后根据我为其创建表的优先级对它们进行排序。但是问题在于,很多 if 语句都有发生的方式。有没有办法重构它们?

示例为:

Create bank txn legs: 
Arrange the legs in a map
Get priority from database
    IF priority present
        Sort legs acc to priority
IF first leg status =  DESTINATION
    Perform destination txn
    IF txn == DESTINATION && SUCCESS
       save success for destination
    ELSE exit;
THEN perform source txn
    IF txn == SOURCE && SUCCESS
       save success for source 
    ELSE exit;  
ELSE IF first leg status = SOURCE
     Perform source txn
     IF txn == SOURCE && SUCCESS
       save success for source
     ELSE exit;
THEN destination txn'
     IF txn == DESTINATION && SUCCESS
       save success for destination
       PERFORM OTHER TXNS IN THREAD:    
     ELSE exit;

0 个答案:

没有答案