java - How to better design class structure for this code -
i making data structure called scalar
. interface declares operations available(like multiply/divide/add/subtract). anyways have 3 different classes implements scalar
. fractionalscalar
represented numerator , denominator , generalscalar
represented string.
normally add accessor scalar
interface double get()
. stuff like
public class fractionalscalar implements scalar { public scalar multiply(scalar other) { return new fractionalscalar(this.get() * other.get()); } .... // other methods }
but works because fractionalscalar represented double. "generalscalar" cant represented numeric value because supposed theoretical value. not sure theoretical best word here meant.
scalar = generalscalar('a'); scalar b = generalscalar('b'); scalar 1 = simplescalar(1); // class extends fractionalscalar , used represent integers scalar 2 = simplescalar(2);
so if want represent 2a two.multiply(a);
the thing im doing supposedly able conduct\validate\represent mathematical proofs.
but since generalscalar doesnt have value have this
public class fractionalscalar implements scalar { scalar multiply(scalar other) { if (other instanceof fractionalscalar) { return new fractionalscalar (this.get() * (fractionalscalar) other.get()); } else if (other instanceof generalscalar) { //cast generalscalar , stuff } }...... }
i dont instanceof if clauses there better way trying accomplish?
you have full dynamic dispatch java dynamic dispatcher on instance, not arguments.
one way rid of instanceof
throwing exception in get()
when scalar cannot compute value. either produce fractionalscalar
or, in presence of exception, generalscalar
regardless of type of scalar. desirable have method hasvalue()
, in scalar
, avoid generating exception.
Comments
Post a Comment