indriya icon indicating copy to clipboard operation
indriya copied to clipboard

Foreign Units must be handled with no Surprises

Open andi-huber opened this issue 6 years ago • 5 comments

Several code fragments assume that any Unit is an (or a subtype of) AbstractUnit.

  1. This might result in ClassCastExceptions, when instead we should throw a proper and more descriptive UnsupportedOperationException.

  2. Some code-paths are simply ignored, when a Unit is not of type AbstractUnit. Its critical to make sure, we properly throw an UnsupportedOperationException instead, to prevent users from running into incorrect calculations. (Calculations must fail instead!)

andi-huber avatar Apr 05 '19 10:04 andi-huber

waiting on #204 to be resolved/merged

andi-huber avatar Apr 05 '19 13:04 andi-huber

There are a few cases which assume AbstractUnit, a few more the RI extension interface ComparableUnit. I would rather throw an IllegalArgumentException or MeasurementException because it is specific to the Measurement RI. UnsupportedOperationException seems only suitable if you want to mark the whole method as unsupported by this implementation.

keilw avatar Apr 10 '19 23:04 keilw

For example when looking at ProductUnit

    @Override
    public UnitConverter getSystemConverter() {
        UnitConverter converter = AbstractConverter.IDENTITY;
        for (Element e : elements) {
            if (e.unit instanceof AbstractUnit) {
                UnitConverter cvtr = ((AbstractUnit<?>) e.unit).getSystemConverter();
                if (!(cvtr.isLinear()))
                    throw new UnsupportedOperationException(e.unit + " is non-linear, cannot convert");
                if (e.root != 1)
                    throw new UnsupportedOperationException(e.unit + " holds a base unit with fractional exponent");
                int pow = e.pow;
                if (pow < 0) { // Negative power.
                    pow = -pow;
                    cvtr = cvtr.inverse();
                }
                for (int j = 0; j < pow; j++) {
                    converter = converter.concatenate(cvtr);
                }
            }
        }
        return converter;
    }

If the ProductUnit contains an element that is not an instance of AbstractUnit, we still return a converter, but we should instead fail, I guess! I believe we have multiple such code fragments that do not behave well, when 'foreign' Units are used.

andi-huber avatar Apr 11 '19 07:04 andi-huber

As an alternative to failing with exceptions, we could instead within RI lookout for places that allow to replace/narrow method arguments Unit<Q> with AbstractUnit<Q>, such that it is clear, what type the RI expects for proper operation.

andi-huber avatar Apr 11 '19 07:04 andi-huber

This may not work in every case, but here the logical solution would be offering getSystemConverter() to the API element Unit instead.

keilw avatar Apr 13 '19 20:04 keilw