Skip to content

Refactor: centralize type handling for simple operations such as add and subtract, and add branch coverage for this #167

Open
@akerfel

Description

@akerfel

In the files FenwickTree.java, Matrix.java and SegmentTree.java (all in the folder \src\com\jwetherell\algorithms\data_structures), there are comments saying TODO: This is ugly and how to handle number overflow?. See example below.

These functions do the same things, therefore some refactoring could decrease code repetition. Specifically, a class could be created which holds functions for adding, subtracting, multiplying and comparing the different types BigDecimal, BigInteger, Long, Double, Float and Integer.

Furthermore, there seems to be no branch coverage for using these different types, since all tests just use Integers. Tests for the different types should be added.

/* TODO: This is ugly and how to handle number overflow? */
if (this.sum instanceof BigDecimal || data.sum instanceof BigDecimal) {
    BigDecimal result = ((BigDecimal)this.sum).subtract((BigDecimal)data.sum);
    this.sum = (N)result;
} else if (this.sum instanceof BigInteger || data.sum instanceof BigInteger) {
    BigInteger result = ((BigInteger)this.sum).subtract((BigInteger)data.sum);
    this.sum = (N)result;
} else if (this.sum instanceof Long || data.sum instanceof Long) {
    Long result = (this.sum.longValue() - data.sum.longValue());
    this.sum = (N)result;
} else if (this.sum instanceof Double || data.sum instanceof Double) {
    Double result = (this.sum.doubleValue() - data.sum.doubleValue());
    this.sum = (N)result;
} else if (this.sum instanceof Float || data.sum instanceof Float) {
    Float result = (this.sum.floatValue() - data.sum.floatValue());
    this.sum = (N)result;
} else {
    // Integer
    Integer result = (this.sum.intValue() - data.sum.intValue());
    this.sum = (N)result;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions