mercredi 27 mars 2019

Java: Best match search on on object with required and optional fields

Assume I have a key/value that has the following structure.

@Value.Immutable
public interface Key {
  EnumFoo required_enum_one;
  EnumBar required_enum_two;
  Optional<boolean> optional_boolean_one;
  Optional<EnumBaz> optional_enum_two; 
} 

@Value.Immutable
public interface Value {
  Message message; 
} 

Assume that I have a key/value mapping, where I have a message value for all the combinations of the required fields, and some combinations of optional fields. For example:

{foo1, bar1, true, baz1 } => msg1
{foo1, bar1, true, <any value except baz1> } => msg2
{foo1, bar2, <any value>, <any value> } => msg3
{foo2, bar2, <any value>, <any value> } => msg4
If I do a look up of {foo1, bar2, false, baz1}, it should resolve to msg3

What would be the best way to implement this? I was thinking of adding a custom @equals to the key where it skips optional matching when it isnt present in mapping collection. As for the mapping collection, I was thinking of a list of key/value tuples which is ordered based on the presence of the optional fields(similar to above code block), so that the key which matches all required fields and most optional fields is selected and the corresponding value is returned?

Is there a better approach? As a bonus, I find myself repeating this pattern for different types. Is there a way to have a reusable solution?

Aucun commentaire:

Enregistrer un commentaire