[ACCEPTED]-Java Serialization with Protocol Buffer-protocol-buffers

Accepted answer
Score: 13

Perspective 1

You write a .proto file and give it to protoc 23 that generates the Builder code. They are 22 suggesting not to add any methods to the 21 generated code. If at all you want some 20 custom behavior to be added to the generated 19 code then WRITE YOUR OWN CLASS WRAPPING 18 the generated code.

For e.g let us say the 17 protoc generated class is MyMessageBuilder. And 16 you wanted to add a method that can take 15 XML input and spitout the protobuff specific 14 message out. You would write a XmlToMyMessageBuilder 13 as below. Here XmlToMyMessageBuilder, your 12 class is wrapping the generated code and 11 adding custom behavior fromXml().

public class XmlToMyMessageBuilder
{
    private final MyMessageBuilder protoBuilder;

    public MyMessage fromXml(byte[] input()
    {
        protoBuilder.setXXX();
    }
}

This is 10 a general good programming principle.

Perspective 2

By 9 providing a intermediary you can also DECOUPLE 8 your code from the underlying serialization 7 mechanism. This allows you to switch the 6 serializer implementations (say you want 5 to serialize a payload where all the data 4 is in string format...where JSON seriazation 3 with compression is a better alternative) with 2 low impact. You could do something like 1 this

public interface MySerializer
{
    boolean serialize(MyDomainObject input);
}

public PBBasedSerializer implements MySerializer
{
    private final MyMessageBuilder protoBuilder;
    ...
}

public JsonBasedSerializer implements MySerializer
{
    private final JSONSerializer jsonSerializer;
    ...
}
Score: 3

It means that you would implement your own 13 class that contains a protocol buffer object 12 as a private field.

Protocol buffer classes 11 are generated from .proto files. These generated 10 classes have all methods to directly manipulate 9 the fields they contain. But they don't 8 have methods that serve higher level operations 7 than just modifying a field.

Your wrapper 6 class can then provide a richer or more 5 restricted interface to users of your API. As 4 any modification of the protocol buffer 3 needs to go through the wrapping object, you 2 have full control about what operations 1 you want to support.

More Related questions