Protocol buffer and OO design

南笙酒味 提交于 2019-12-03 05:43:23

I have no experience with protocol buffers, but I would not recommend implementing your domain objects tailored to a specific serialization/transfer framework. You might regret that in the future.

The domain objects and logic of a software application should be as independent as possible from specific implementation issues (in your case serialization/transfer), because you want your domain to be easy to understand and be reusable/maintainable in the future.

If you want to define your domain objects independent of serialization/transfer, you have two options:

  1. Before serialization/transfer, you copy the information to protocol buffers specific objects and send them to your server. There you would have to copy the information back to your domain objects.
  2. Use a non-protocol serialization library like Kryo or ProtoStuff to directly transfer your domain objects to the server.

The disadvantages of option 1 are that your domain is defined two times (which is undesirable with respect to modifications) and the copying of information (which produces error-prone and non maintainable code).

The disadvantages of option 2 are that you lose schema evolution (although ProtoStuff apparently supports it) and the complete (potentially large) object graph is serialized and transferred. Although you could prune the object graph (manually or with JGT) before serialization/transfer.

We've made a protobuf-converter to solve the problem of transformation of your Domain Model Objects into Google Protobuf Messages and vice versa.

How to use it:

Domain model classes that have to be transformed into protobuf messages must satisfy conditions:

  • Class has to be marked by @ProtoClass annotaion that contains reference on related protobuf message class.
  • Class fields has to be marked by @ProtoField annotaion. These fields must have getters and setters.

E.g.:

@ProtoClass(ProtobufUser.class)
public class User {

    @ProtoField
    private String name;
    @ProtoField
    private String password;

    // getters and setters for 'name' and 'password' fields
    ...
}

Code for conversion User instance into related protobuf message:

User userDomain = new User();
...
ProtobufUser userProto = Converter.create().toProtobuf(ProtobufUser.class, userDomain);

Code for backward conversion:

User userDomain = Converter.create().toDomain(User.class, userProto);

Conversion of lists of objects is similar to single object conversion.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!