如何重构代码消除Sonar警告,将认知复杂度从59降至允许的15?
Refactoring to Reduce Cognitive Complexity
First, let's break down why your original code has such high cognitive complexity: it’s packed with nested conditionals, duplicate validation logic, and all the logic is crammed into a single loop. By extracting responsibilities into separate methods and using early returns, we can drastically simplify this while preserving all your original business rules.
Here’s the refactored version, which will bring your cognitive complexity well below the 15 threshold:
// Cleaned-up main loop for (int i = 0; i < dataList.getTotalCount(); i++) { TariffRateGroupDTO listObj = (TariffRateGroupDTO) dataList.get(i); validateTariffRateGroup(listObj, i); } // Handles full validation for a single group entry private void validateTariffRateGroup(TariffRateGroupDTO group, int rowIndex) throws ValidationException { // Exit early if this group doesn't need validation if (!isUpdateMode(group)) { return; } String flightCondition = group.getFlightCondition(); boolean wasFlightConditionFetched = false; // Fetch missing flight condition if needed if (flightCondition == null || flightCondition.isEmpty()) { TariffRateGroupDTO fc = getFlightCondition(group.getId(), group); flightCondition = fc.getFlightCondition(); wasFlightConditionFetched = true; } // No flight condition to validate? Exit early if (flightCondition == null) { return; } // Run validation and handle errors ArrayList<?> validationErrors = checkFlightCondition(flightCondition); if (isValidationPassed(validationErrors)) { return; } ValidationError firstError = (ValidationError) validationErrors.get(0); throw createValidationException(firstError, rowIndex, wasFlightConditionFetched); } // Check if the group is in update mode private boolean isUpdateMode(TariffRateGroupDTO group) { return group != null && "U".equals(group.getTxnMode()); } // Verify if validation returned no errors private boolean isValidationPassed(ArrayList<?> validationErrors) { return validationErrors == null || validationErrors.isEmpty(); } // Build the appropriate exception with optional row number private ValidationException createValidationException(ValidationError error, int rowIndex, boolean includeRowNumber) { ValidationException ve = new ValidationException(); StringBuilder errorMessage = new StringBuilder(error.getMessage()); if (includeRowNumber) { errorMessage.append(" at row [").append(rowIndex + 1).append("]"); } ve.setErrorCode(errorMessage.toString()); return ve; }
Key Refactoring Choices:
- Single-Responsibility Methods: Each helper method does one specific job (checking update mode, validating results, creating exceptions) which makes the code easier to read, test, and modify later.
- Early Returns: Instead of nesting conditionals, we exit the method as soon as a condition isn’t met. This flattens the code structure and reduces the mental effort needed to follow the logic.
- Eliminate Duplication: The error-handling logic was repeated in both branches of the flight condition check—now it’s handled once in a single place.
- Explicit State Tracking: We use
wasFlightConditionFetchedto track whether we need to add the row number to the error message, replacing the nested conditional that handled this before.
This approach keeps all your original behavior intact while making the code far more maintainable and compliant with Sonar’s complexity rules.
内容的提问来源于stack exchange,提问作者user1896796
相关产品推荐
相关产品推荐

