How can I streamline complex nested protobuf validation in C++?
I'm using Google protocol buffers in a messaging application. The protos are often nested several levels deep, and we have taken Google's advice and made them all optional. The protos can describe many different types of overlapping messages - i.e. a message of Type == X should contain the member my_X, Type == Y should contain my_Y. Further, certain combinations of fields impose other restrictions on which fields should be present and what values they should have. Changing the proto's structure开发者_Python百科 is beyond the scope of what I can do.
Right now, all of this validation is in a mess of if..else statements. If the cases didn't overlap, that might be workable, but validation cases can impose different restrictions on a certain field, so it can get pretty ugly. Is there a better way? My goal is to make the code more maintainable. I've looking into functors/predicates a little, and it seems like that may simplify the problem, but it still seems like it will be a mess.
If the code starts to contain too many ifs and elses then sometimes a table-driven approach is the solution. Chapter 18 of Code Complete Edition 2 does a good job explaining the concept with plenty of examples. You can find a few examples in this article as well.
Hoping to help.
精彩评论