The Value field can be one of four different types - the best design?

I have a class called "DataModel" or something that basically represents a unit of data, which can be either a string, or a number, or a date or a boolean with different (identical) attributes.

What is the best way to write this model?

  • Enter a value of type Object

    interface DataModel {
       Object getValue();  // cast to whatever is needed
       int getValueType(); // uses four constants
    }
    
  • They have four different implementations: "StringModel", "NumberModel", etc., each with its own method, "getValue ()". This means that if you have a DataModel, you will need to specify the correct model to get the value.

    interface DataModel {
       int getValueType();
    }
    interface NumberDataModel extends DataModel {
      Integer getValue();
    }
    ...
    
  • There are four different methods, each of which throws an exception if caused by the wrong type of value:

    interface DataModel {
      String getStringValue();
      Integer getIntegerValue();
      ...
      int getValueType();
    }
    
  • generics. , ... , IllegalStateException , T 4 ...

    interface DataModel<T> {
      T getValue();
    }
    
  • . .;)

+3
5

4 - - , , - - , .

+3

1 , / , . , , , int.

, 2 4. 4 , getValueType() , , .

, 3 - , - (, JDBC), , .

4 getValueType() .

+2

.

, - getValue(), , getValue() .

, , . instanceof getValueType(), getValueType, . getValueType, , , int.

+2

4 - . .

, , 4 2. :

interface DataModel<T> {
   T getValue();
}
interface NumberDataModel extends DataModel<Number> {
   // empty
}
class NDM implements NumberDataModel {
   Number getValue() { return ... }
}

DataModel / .

+2

As a universal alternative, you can use Class Literals as Runtime tokens and use newInstance()to get data instances with a security type. This allows you to check the compilation time using general parameters and check the runtime through isAssignableFrom().

0
source

Source: https://habr.com/ru/post/1728304/


All Articles