I have a class called "DataModel" or something, which is basically a unit of data which can be either a string or a number or a date or a boolean with various (identical) attributes.
What is the best way to write this model?
Have the value be of type Object
interface DataModel { Object getValue(); // cast to whatever is needed int getValueType(); // uses four constants }
Have four different implementations "StringModel", "NumberModel", etc., each with their own typed "getValue()" method. This means if you had a DataModel, you'd have to cast to the correct Model to get to the value.
interface DataModel { int getValueType(); } interface NumberDataModel extends DataModel { Integer getValue(); } ...
Have four different methods, each throwing an exception if called for a wrong value type:
interface DataModel { String getStringValue(); Integer getIntegerValue(); ... int getValueType(); }
Use generics. This has the downside that I theoretically could have any object of any type...on the other hand I could just throw an IllegalStateException in the constructor if T was not one of the 4 allowed types...
interface DataModel<T> { T getValue(); }
It doesn't matter. Any of the above. ;)