Protocol buffer and OO design

后端 未结 2 1154
小蘑菇
小蘑菇 2021-02-05 08:10

I\'m using protocol buffer as a wire data-format in a client-server architecture. Domain objects (java beans) will go through following life-cycle.

  1. Used in client
相关标签:
2条回答
  • 2021-02-05 08:49

    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.

    0 讨论(0)
  • 2021-02-05 08:51

    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.

    0 讨论(0)
提交回复
热议问题