patternjavaMinor
Value class representing different types
Viewed 0 times
valuedifferenttypesclassrepresenting
Problem
I have a
It implements integer, real, vertor, enumeration and boolean. Some of the fields,
and methods are implemented conditionally, like
and so on.
Despite promoters of OOP and design patterns state that OOP polymorphism is not any better than procedural case-based one, it looked very ugly to me. Additionally, I felt like polymorphism can eliminate the switch checking overhead and reduce memory footprint. I me
Value class that may represent many different types:private BigInteger fNum;
private BigDecimal fReal;
private ArrayList fArrayValues;
private int fArrayOffset;
private HashMapArray fRecordValues;
private boolean fIsCharLiteral;
private int fEnumOrd;
private char fCharLiteral;
private File fFile;
private StaticValue fLeft, fRight, fAscending;
private boolean fIsBuiltinBool = false;
private boolean fTruthValue;It implements integer, real, vertor, enumeration and boolean. Some of the fields,
fIsBuiltinBool and fIsCharLiteral hint which type it implements. Instances are created like:public StaticValue(ValueBuilder aBuilder) {
super(aBuilder.getType());
fId = aBuilder.getId();
fIsCharLiteral = aBuilder.isCharLiteral();
fCharLiteral = aBuilder.getCharLiteral();
fEnumOrd = aBuilder.getEnumOrd();
fNum = aBuilder.getNum();
fFile = aBuilder.getFile();
fReal = aBuilder.getReal();
fLeft = aBuilder.getLeft();
fRight = aBuilder.getRight();
fAscending = aBuilder.getAscending();
TypeStatic type = aBuilder.getType();
switch (type.getCat()) {
case ARRAY:
fArrayOffset = init ...
fArrayValues = init...
case RECORD:
fRecordValues = new HashMapArray();
init ...
case INTEGER:
if (fNum == null) throw Exception
break;and methods are implemented conditionally, like
public String toString() {
if (fIsBuiltinBool) {
return "" + fTruthValue;
}
try {
Type type = getType();
switch (type.getCat()) {
case ARRAY: show fArrayValues
case RECORD:
buf = new StringBuilder();
show fieldsand so on.
Despite promoters of OOP and design patterns state that OOP polymorphism is not any better than procedural case-based one, it looked very ugly to me. Additionally, I felt like polymorphism can eliminate the switch checking overhead and reduce memory footprint. I me
Solution
Have you considered using Generic type attributes?
abstract class StaticValue {
T payload;
//...
}
class Real extends StaticValue { /*...*/ }Code Snippets
abstract class StaticValue<T> {
T payload;
//...
}
class Real extends StaticValue<BigDecimal> { /*...*/ }Context
StackExchange Code Review Q#18016, answer score: 5
Revisions (0)
No revisions yet.