Legacy Code Refactoring [closed]

Posted on

Problem

I have a legacy piece of code and trying to simplify it. It’s very tightly coupled. The problem is one method is called from another and other from another and so on this chain continues. Would someone please help me out to make it better by reviewing it or suggesting any approach or design pattern to handle this type of problem.

@Override
public Boolean doCvcVerification(TransactionVO tvo) throws SQLException, CommonBaseException {

    if (processCvc(tvo)) {
        return doCvv2Verification(tvo);
    }
    else {
        MessageVO mvo = tvo.getRequestMessage();
        if (!CommonUtils.isNullOrEmptyStr(mvo.getCvv2Value())) {
            tvo.setCvc2ResultCode(CvcResult.CVC2_NO_PROCESSED.code());
            LGR.info(LGR.isInfoEnabled() ? "i2c CVV2 Result Code [" + tvo.getCvc2ResultCode() + "]" : null);
        }
        else {
            LGR.info(LGR.isInfoEnabled() ? "CVV2 is [NOT FOUND/UN-AVAILABLE] in request message for verification." : null);
        }

        return Boolean.FALSE;
    }
}

@Override
public Boolean processCvc(TransactionVO tvo) throws SQLException, CommonBaseException {

    String track1 = tvo.getRequestMessage().getTrack1();
    String track2 = tvo.getRequestMessage().getTrack2();

    boolean track1Present = CommonUtils.isNullOrEmptyStr(track1) ? Boolean.FALSE : Boolean.TRUE;
    boolean track2Present = CommonUtils.isNullOrEmptyStr(track2) ? Boolean.FALSE : Boolean.TRUE;

    Boolean serviceResponse;

    try {

        // Both tracks track1 & track2 not found
        if (!track1Present && !track2Present) {
            LGR.info(LGR.isInfoEnabled() ? "Both DE-45(Track 1) and DE-35(Track 2) are not present in request. Tag 04.29 will be N" : null);
            tvo.setCvcPresent(false);
            buildResponseForCvc(tvo, APPROVED, DescriptionCode.CVC_BOTH_TRACKS_NOT_PRESENT, CvcResult.CVC_NOT_RECEIVED);
            serviceResponse = Boolean.TRUE;
        }

        // Both tracks track1 & track2 found
        else if (track1Present && track2Present) {
            LGR.debug(LGR.isDebugEnabled() ? "Both Tracks are found for Card No. '" + tvo.getMaskedCardNoWithSerial() + "'" : null);
            int statusTrack1 = parseAndVerifyTrackData(tvo, track1, 1);
            if (statusTrack1 != HSM_SUCCESS) {
                int statusTrack2 = parseAndVerifyTrackData(tvo, track2, 2);
                if ((statusTrack1 == HSM_FAIL && statusTrack2 == NOT_FOUND) || (statusTrack1 == HSM_FAIL && statusTrack2 == HSM_FAIL) || (
                        statusTrack1 == NOT_FOUND && statusTrack2 == HSM_FAIL)) {
                    populateCvcHsmCode(tvo);
                    serviceResponse = Boolean.FALSE;
                }
                else if (statusTrack1 == NOT_FOUND && statusTrack2 == NOT_FOUND) {
                    buildResponseForCvc(tvo, BAD_CVC1, CvcResult.CVC1_NOT_MATCH_INCOMPLETE_TRACK.descCode(),
                            CvcResult.CVC1_NOT_MATCH_INCOMPLETE_TRACK);
                    serviceResponse = Boolean.FALSE;
                }
                else {
                    buildResponseForCvc(tvo, APPROVED, CvcResult.CVC1_MATCH.descCode(), CvcResult.CVC1_MATCH);
                    serviceResponse = Boolean.TRUE;
                }
            }
            else {
                buildResponseForCvc(tvo, APPROVED, CvcResult.CVC1_MATCH.descCode(), CvcResult.CVC1_MATCH);
                serviceResponse = Boolean.TRUE;
            }
        }

        // One track either 1 or 2 found
        else {
            int statusTrack;
            int trackNo = track1Present ? 1 : 2;
            String track = track1Present ? track1 : track2;

            LGR.debug(LGR.isDebugEnabled() ? "Track " + trackNo + " is found for Card No. '" + tvo.getMaskedCardNoWithSerial() + "'" : null);
            statusTrack = parseAndVerifyTrackData(tvo, track, trackNo);

            if (statusTrack == HSM_FAIL) {
                populateCvcHsmCode(tvo);
                serviceResponse = Boolean.FALSE;
            }
            else if (statusTrack == NOT_FOUND) {
                buildResponseForCvc(tvo, BAD_CVC1, CvcResult.CVC1_NOT_MATCH_INCOMPLETE_TRACK.descCode(), CvcResult.NULL);
                serviceResponse = Boolean.TRUE;
            }
            else {
                buildResponseForCvc(tvo, APPROVED, CvcResult.CVC1_MATCH.descCode(), CvcResult.CVC_MATCHED);
                serviceResponse = Boolean.TRUE;
            }
        }

        return serviceResponse;
    }
    catch (SQLException e) {
        buildResponseForCvc(tvo, DONOT_HONOR, CvcResult.CVC1_NOT_PROCESSED.descCode(), CvcResult.CVC1_NOT_PROCESSED);
        LGR.warn(e.getMessage(), e);
        throw e;
    }
}

protected int parseAndVerifyTrackData(TransactionVO tvo, String track, int trackNo) throws SQLException, CommonBaseException {
    int status1 = HSM_FAIL;

    TrackVO trackVO = parseTrack(tvo, track, trackNo, getTrackFormat());

    if (null != trackVO) {

        status1 = verifyTrackData(tvo, trackVO);

        // Alternate Track Logic
        if (status1 != HSM_SUCCESS && isAlternateTrackPresent() && null != getOldTrackFormat()) {
            LGR.warn("CVC1 hasn't been verified by Format [" + getTrackFormat() + "], so verifying it again by Old Format ["
                    + getOldTrackFormat() + "] in Track No." + trackNo);
            trackVO = parseTrack(tvo, track, trackNo, getOldTrackFormat());
            LGR.debug(LGR.isDebugEnabled() ? trackVO + " from Track " + trackNo + " using Old Track Format: " + getOldTrackFormat() : null);
            int status2 = verifyTrackData(tvo, trackVO);

            if (status1 == HSM_FAIL && status2 == NOT_FOUND) {
                return HSM_FAIL;
            }
            else if (status1 == HSM_FAIL && status2 == HSM_FAIL) {
                return HSM_FAIL;
            }
            else if (status1 == NOT_FOUND && status2 == HSM_FAIL) {
                return HSM_FAIL;
            }
            else if (status1 == NOT_FOUND && status2 == NOT_FOUND) {
                return NOT_FOUND;
            }
            else {
                return status2;
            }
        }
        else {
            return status1;
        }

    }

    return status1;
}

protected TrackVO parseTrack(TransactionVO tvo, String track, int trackNo, String trackFormatId) throws SQLException, CommonBaseException {

    TrackVO trackVO = null;
    TrackParsingReqVO trackParsingReqVo = new TrackParsingReqVO(tvo.getInstanceId(), track, trackNo, trackFormatId);

    trackParsingReqVo.setCardBin(tvo.getCardBin());

    if (isContactLessTrans(tvo)) {
        trackParsingReqVo.setIsUseContactlessFormat(true);
    }

    TrackParsingRespVO trackParsingRespVo = (TrackParsingRespVO) new TrackParsingUtility().execute(trackParsingReqVo);
    trackVO = trackParsingRespVo.getTrackVO();

    tvo.setTrackServiceCode(trackVO.getServiceCode());

    if (trackNo == 1) {
        tvo.setTrackChFinalName(trackVO.getCardHolderName());
        tvo.setTrackChFinalNameModified(CommonBusinessUtils.formTrack(trackVO.getCardHolderName()));
        LGR.debug(LGR.isDebugEnabled() ? CommonUtils.concatValues("Track ", trackNo, " is tokenized for CardholderName: Original [",
                tvo.getTrackChFinalName(), "], Modified [", tvo.getTrackChFinalNameModified(), "]") : null);
    }
    return trackVO;
}


protected int verifyTrackData(TransactionVO tvo, TrackVO trackVO) throws SQLException {
    if (null != trackVO) {
        if (!CommonUtils.isNullOrEmptyStr(trackVO.getServiceCode())) {
            String serviceCode = trackVO.getServiceCode().trim();
            if (CommonUtils.isNotNullAndValidInt(serviceCode)) {
                setContactLessTrans(tvo.getRequestMessage(), serviceCode);
            }
            else {
                LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid ServiceCode [" + serviceCode + "]");
                setHsmRespCode(HSM_DECLINE);
                return HSM_FAIL;
            }
        }

        if (!CommonUtils.isNullOrEmptyStr(trackVO.getCvc())) {
            String cvc = trackVO.getCvc().trim();
            if (!CommonUtils.isNotNullAndValidInt(cvc)) {
                LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid CVC [" + cvc + "]");
                setHsmRespCode(HSM_DECLINE);
                return HSM_FAIL;
            }
        }

        if (!CommonUtils.isNullOrEmptyStr(trackVO.getPanSeqNo())) {
            String panSeqNo = trackVO.getPanSeqNo().trim();
            if (!CommonUtils.isNotNullAndValidInt(panSeqNo)) {
                LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid PanSeqNo [" + panSeqNo + "]");
                setHsmRespCode(HSM_DECLINE);
                return HSM_FAIL;
            }
        }

        if (!CommonUtils.isNullOrEmptyStr(trackVO.getAtc())) {
            String atc = trackVO.getAtc().trim();
            if (!CommonUtils.isNotNullAndValidInt(atc)) {
                LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid ATC [" + atc + "]");
                setHsmRespCode(HSM_DECLINE);
                return HSM_FAIL;
            }
        }

        if (!CommonUtils.isNullOrEmptyStr(trackVO.getUn())) {
            String un = trackVO.getUn().trim();
            if (!CommonUtils.isNotNullAndValidInt(un)) {
                LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid UN [" + un + "]");
                setHsmRespCode(HSM_DECLINE);
                return HSM_FAIL;
            }
        }

        if (!CommonUtils.isNullOrEmptyStr(trackVO.getUnl())) {
            String unl = trackVO.getUnl().trim();
            if (!CommonUtils.isNotNullAndValidInt(unl)) {
                LGR.error("Incomplete Track-" + trackVO.getTrackNo() + ": Null or Invalid UNL [" + unl + "]");
                setHsmRespCode(HSM_DECLINE);
                return HSM_FAIL;
            }
        }

        //validates expiration
        Integer expValidation = validateTrackExpiry(tvo, trackVO.getTrackNo(), trackVO.getExpiryValue());
        if (expValidation == HSM_SUCCESS) {
            if (!validateSecureElements(tvo, trackVO)) {
                return NOT_FOUND;
            }
            else {
                tvo.setCvcPresent(true);
                return verifyCvc(tvo, trackVO);
            }
        }
        else {
            return expValidation;
        }
    }
    else {
        LGR.error("Incomplete Track-: Null TrackVO");
        setHsmRespCode(HSM_DECLINE);
        return HSM_FAIL;
    }
}

@Override
protected boolean validateSecureElements(TransactionVO tvo, TrackVO trackVO) {
    boolean valid = false;
    try {
        if ((CommonUtils.isNullOrEmptyStr(trackVO.getCvc()) || CommonUtils.isNullOrEmptyStr(trackVO.getServiceCode()))
                && (!tvo.isCardSwiped() || tvo.isCardNotPresentTrans())
                && "1".equals(tvo.getRequestMessage().getCvv2Indicator())) {
            LGR.info("CVC1/iCVV not received in track data. CVV2 will be evaluated.");
            valid = true;
        }
        else {
            valid = super.validateSecureElements(tvo, trackVO);
        }

    }
    catch (CommonBaseException e) {
        LGR.info("Someone introduced a shitty exception in whole hierarchy and I have to catch it here. This is anti pattern. But who follows!");
    }

    return valid;
}

@Override
protected int verifyCvc(TransactionVO tvo, TrackVO trackVo) {


    if(CommonUtils.isNullOrEmptyStr(trackVo.getCvc())){
        return NOT_FOUND;
    }

    trackVo.setExpiryDate(CommonDateUtils.parseDate(CommonDateConstants.DATE_FORMAT_yyMM, trackVo.getExpiryValue()));
    CvcType cvcType = getCvc1Type(tvo);
    setReceivedCvcType(cvcType);

    CvcHsmValidation cvcValidator = CvcHsmFactory.getInstance().getCvcHsmValidationObj(cvcType, this, tvo, trackVo);
    LGR.info(LGR.isInfoEnabled() ? "Validating " + cvcType : null);
    CvcHsmResponse respCvc = cvcValidator.verifyCvc();
    LGR.info(LGR.isInfoEnabled() ? cvcType + " validation response: " + respCvc : null);

    if (APPROVED.equals(respCvc.getRespCode())) {
        if (!CommonUtils.isNullOrEmptyStr(trackVo.getExpiryValue())) {
            tvo.setExpiryDateFromTrans(trackVo.getExpiryValue(), CommonDateConstants.DATE_FORMAT_yyMM);
        }
        setCvcValidationStatus(CvcValidationResult.MATCHED);
        return HSM_SUCCESS;
    }
    else {
        setCvcValidationStatus(CvcValidationResult.NOT_MATCHED);
        return HSM_FAIL;
    }
}


@Override
public Boolean doCvv2Verification(TransactionVO tvo) throws SQLException {
    String cardBin = tvo.getCardBin();
    Boolean serviceResponse = Boolean.FALSE;


    // checking flag of process_cvv2 from table of multi-instance
    if (CommonBaseConstants.OPTION_YES.equalsIgnoreCase(getCvcValidationDao().getProcessCvv2(cardBin))) {
        serviceResponse = processCvv2(tvo);

    }
    else {
        LGR.debug(LGR.isDebugEnabled()
                ? CommonUtils.concatValues(
                "CVV2 will be processed as normal as process_cvv2 flag in table is either 'N' or null for card bin: ", cardBin)
                : null);
    }
    return serviceResponse;
}

Complete source code is available at repl

Solution

A small improvement I can make is to remove the if-else blocks with if like the below code , This will improve the readability of the code

        if (processCvc(tvo)) {
           return doCvv2Verification(tvo);
        }
        MessageVO mvo = tvo.getRequestMessage();
        if (CommonUtils.isNullOrEmptyStr(mvo.getCvv2Value())){
              LGR.info(LGR.isInfoEnabled() ? "CVV2 is [NOT FOUND/UN-AVAILABLE] in request message for verification." : null);
              return Boolean.FALSE;

         }
        tvo.setCvc2ResultCode(CvcResult.CVC2_NO_PROCESSED.code());
        LGR.info(LGR.isInfoEnabled() ? "CVV2 Result Code [" + tvo.getCvc2ResultCode() + "]" : null);
        return Boolean.FALSE;

Leave a Reply

Your email address will not be published.