mercredi 23 septembre 2020

Avoiding if-else with Protobuf generated enums using visitor pattern

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 pattern that could solve this issue.

Aucun commentaire:

Enregistrer un commentaire