1

Let's say I have a proto object as follows:

oneof sample {
     string str = 1;
     int64 i = 2;
     ... (many other fields inside oneof)
}

The autogenerated java code will generate enum for sample named SampleCase which contains

enum SampleCase {
    STR(1)
    I(2)
    ...
}

Now on the application side, I want to call methods on different objects based on the type of enum SampleCase. A naive way is to do if-else:

if(case == SampleCase.STR) {
    obj1.call();
} else if(case == SampleCase.I) {
    obj2.call();
} else if(....)
...

Visitor pattern seems a good fit here to avoid if-else. I looked at this, but that would require modifying the enums and I don't have access to modify the protobuf generated enums. Any approach how to proceed further?

Also I am open to any other design patterns that could solve this issue.

Raj
  • 23
  • 4
  • Switch case supports [enum types](https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html). – jaco0646 Sep 23 '20 at 14:37
  • @jaco0646 I am looking for a general solution. I have this if-else's in many places in my code. Having switch case doesn't really solve anything. – Raj Sep 23 '20 at 15:25

1 Answers1

1

One option to avoid having, quoting you, "I have this if-else's in many places in my code". Is to create your own domain objects that implement the Visitor pattern.

You convert the Proto generated objects to the domain object in one place right when you receive them, and after that you can use visitor pattern everywhere else instead of the switch cases / if-else.

You will have to depend on a switch / if-else case anyway, but that will be centralized in one place of conversion, instead of all over the code.

This will also enable you to decouple all your from the proto classes.