java - Generic class for operations on Number -
i writing java class represent range. make more general range can number type, 2 values v1 , v2, must in same number type.
although can comparison on them, cannot add or subtract values. know operation on 2 different number types cause problem (e.g. float + integer), , subclasses of number, e.g. biginteger , bigdecimal. in case, v1 , v2 should of same type.
class range<t extends number & comparable<t>> { public t v1; public t v2; public range(t v1, t v2) { if (v1.compareto(v2) > 0) throw new illegalargumentexception("value-1 must smaller or equal value-2."); this.v1 = v1; this.v2 = v2; } public t length() { return v2 - v1; // compilation error } }
recently come idea this:
public t add(t t1, t t2) { if (t1 instanceof integer) { // ... } if (t1 instanceof long) { // ... } }
but there better design create range class? thanks!
make range
, length()
abstract. note v1
, v2
should protected.
abstract class range<t extends number & comparable<t>> { protected t v1; protected t v2; public range(t v1, t v2) { if (v1.compareto(v2) > 0) throw new illegalargumentexception("value-1 must smaller or equal value-2."); this.v1 = v1; this.v2 = v2; } public abstract t length(); }
extend
range class specific types :
class integerrange extends range<integer> { @override public integer length() { return v2 - v1; } }
this in line open-closed
principle. class should open extension, closed modification. using instanceof
checks easiest way go against principle since range
need modified each new type has support. should avoided in case.
Comments
Post a Comment