In YAML, I have a structure similar to the one below, which is to be deserialized in Java and parsed:
events:
- causes:
- CAUSE_ONE
- CAUSE_TWO
effects:
- EFFECT_ONE
- EFFECT_TWO
- causes:
- CAUSE_THREE
effects:
- EFFECT_THREE
This translates into an array of maps, where each map contains two keys - causes and effects, and the value of these keys is an array of strings. What I am attempting to achieve is for a single object to have one or more events. Each event consists of one or more causes which trigger one or more effects. In the example above, when both CAUSE_ONE and CAUSE_TWO conditions are met, EFFECT_ONE and EFFECT_TWO are triggered. When CAUSE_THREE condition is met, EFFECT_THREE is triggered.
In Java, this would be either Map<String, String>[] or List<Map<String, String>>. When all conditions in the causes entry are successfully met, each effect in the effects entry is initiated.
I want to be able to deserialize the YAML data in Java so that a single object can have a number of events that, when a series of conditions (causes) are met, the corresponding effects are triggered. Is there a better way of structuring the YAML above, or a way I can achieve this without using an array of maps?
Depending on the circumstances a list will be inefficient. If you can calculate the CAUSES applicable to a certain input, you have to walk over the list of events to find a match. In that case you are better of with:
events:
[CAUSE_ONE, CAUSE_TWO]:
- EFFECT_ONE
- EFFECT_TWO
[CAUSE_THREE]:
- EFFECT_THREE
where you use the calculated CAUSES to look up the effects. This is valid YAML, but relies on the parser/language combination to be able to handle sequences as keys for representation of mappings in the specific language ¹.
If you cannot calculate up-front and you have to check all events because multi ones can be apply, this mapping is comparable to a list.
Only in the case you cannot predetermine any of the CAUSES based on the input and if you can exit early when finding a match it makes sense to have a list (and order it based on expected input). In all other cases a mapping of some sort (even to chunks of the event list) is going to be more efficient for all but small numbers (because calculating the hash for the mapping and doing a lookup is more efficient than walking a list and doing potentially many more checks)
¹I am not familiar with JAVA parsers and how compliant they are. For Python the PyYAML cannot handle this, but ruamel.yaml (of which I am the author) can.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With