mardi 6 mars 2018

Shorten a method with StringBuilder

I have a method that at the first, checks the some conditions and if this conditions is false, method continues form StringBuilder and then returns result. If this conditions is true, method immediately returns result.

public String format(DivisionResult divisionResult) {
    StringBuilder result = new StringBuilder();

    // -------change-----------------------------
    if (divisionResult == null || divisionResult.getDivisor() == 0) {
        return "";
    }
    if (divisionResult.getDividend() == 0) {
        return "0";
    }
     // -------change-----------------------------
    int[] multiplyResult = divisionResult.getMultiplyResult();
    int[] remainderNumbers = divisionResult.getRemainderNumber();
    int remainderElementLength = remainderNumbers.length;

    for (int i = 0; i < remainderElementLength; i ++) {
        if (i == remainderElementLength - 1) {
            int indent = (remainderNumbers[i] != 0) ? 1 : 0;
            result.append(String.format("%" + (i + indent) + "s", remainderNumbers[i])).append("\n");
            break;
        }
        if (multiplyResult[i] != 0) {
            result.append(_formLastSection(remainderNumbers[i], multiplyResult[i], i));
        }
    }

    modify(divisionResult, result);
    return result.toString();
}

How to shorten this method uses next expression instead of the first if-else block

StringBuilder result = checkBaseConditions(divisionResult)

Aucun commentaire:

Enregistrer un commentaire