I've the following classes: TypeAHandler, TypeBHandler,...
Each handler can turnOn or turnOff a list of object ids (e.g. handler for type A calls microservice, handler for Type B modifies DB entry).

I'm now trying to design a nice external API so a user can construct a set of different types and say e.g. typeA id {1,2} turn on, typeA id {3,4} turn off, typeB id {1} turn on. So the API needs to dispatch to the right handler based on the type.

So something like this:

StateSet stateSet = new StateSet();
stateSet.addObject(MyTypes.TYPE_A, "ID1", State.ON);
stateSet.addObject(MyTypes.TYPE_A, "ID2", State.ON);
stateSet.addObject(MyTypes.TYPE_A, "ID3", State.OFF);
stateSet.addObject(MyTypes.TYPE_A, "ID4", State.OFF);
stateSet.addObject(MyTypes.TYPE_B, "ID1", State.OFF);
// addObject
map.computeIfAbsent(type, new ArrayList<>()).add(new OnOffId(id, state));

This already looks a bit ugly. But now at least I've a List for multiple types.

And then my current dispatch

for (var entry : map.entrySet()) {
  switch (entry.getKey()) {
     when MyTypes.TYPE_A:
     when MyTypes.TYPE_B:

But I feel like there's a much more elegant way. I could have a map of type->handler class and a Handler interface. Is that better? Any comments on making the StateSet more convenient, like a startObject endObject?


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.