0

I have a situation where I'd like to allow a user to complete a form, where the input data is a list of either String values or Boolean values. This is very much like the Settings list on any mobile phone, a series of String values and toggles.

So, I have a Field object defined as such:

public class Field<T> {
    private T value;
    ...
    private T getValue() {
        return value;
    }
}

The problem is when I go to display these in a RecyclerView or just grab the values from a Map, there is no safe way to know what type the value is, String or Boolean.

Because of this, I end up with a lot of (String)field.getValue() and ((Field<String>)field).setValue("someString"). Is there any way to avoid casting entirely? I am totally open to changing my design approach to this Field object, I just want it to be clean.

I have contemplated having methods like getStringValue() and getBooleanValue() so that the caller knows it's getting either a String or Boolean at runtime, but this would result in each field having one method that returns a valid object, while the others return null. I want the caller to not have to know what it's getting back.

Thanks for your help!

Update

Here's an example of how I would access the fields from a LinkedHashMap and create a Person object with them:

// Create the map in one place
LinkedHashMap<String, Field> fields = new LinkedHashMap<(PERSON_FIELDS_NUM);
fields.put(Constants.Field.FIRST_NAME_KEY, new Field(Constants.Field.FIRST_NAME_KEY, "First Name", "Tap to enter"));
fields.put(Constants.Field.LAST_NAME_KEY, new Field(Constants.Field.LAST_NAME_KEY, "Last Name", "Tap to enter"));

// ...Grab fields in another
Person person = new Person();
Field firstName = this.fields.get(Constants.Field.FIRST_NAME_KEY);
Field lastName = this.fields.get(Constants.Field.LAST_NAME_KEY);
person.setFirstName((String)firstName.getValue());
person.setLastName((String)lastName.getValue());
Brandon
  • 1,886
  • 2
  • 17
  • 28
  • It's really hard to answer without more context. Can you show how you're creating and using these fields? – shmosel Nov 17 '17 at 01:57
  • @shmosel I added more context! – Brandon Nov 17 '17 at 02:02
  • Why is it necessary to store the data in a map in the first place? Why not use a proper model instead? And what's with all the raw types? – shmosel Nov 17 '17 at 02:04
  • What kinda proper model do you mean? What would you do instead? @shmosel If I was just binding it to a simple view to display, a simple viewmodel would be easy, but being I want to display this nicely in a RecyclerView, we would usually pass in a data structure that can be be boiled down to a Collection for the adapter to reference – Brandon Nov 17 '17 at 04:41

0 Answers0