Search code examples
protocol-buffers

Avoiding code duplication in protobuf design


message Foo3D {
  optional string sha = 1;

  optional Type type = 2;

  optional Vector3D field_1 = 4;

  optional Vector3D field_2 = 5;
}

message Foo2D {
  optional string sha = 1;

  optional Type type = 2;

  optional Vector2D field_1 = 4;

  optional Vector2D field_2 = 5;
}

message FooData {
  optional Foo2D = 1;

  optional Foo3D = 2;
}

message AllFooData {
  repeated FooData foo_data = 1;
}

I'm serializing a templated data type which can be of dimension 2 or 3 but that has identical functionality otherwise. Is there a more synthetic way to represent its protobuf definition and avoid code duplication? Perhaps something creating a wrapper for field_1 and field_2? the dimensionality of field_1 and field_2 can be deduced from its type field


Solution

  • I think this is the best way to reuse as much as possible and avoid duplication

    message FooData {
      optional string sha = 1;
    
      optional Type type = 2;
     
      message Data2D {
        optional Vector2D field_1 = 1
    
        optional Vector2D field_2 = 2
      }
    
      message Data6D {
        optional Vector6D field_1 = 1
    
        optional Vector6D field_2 = 2
      }
    
      optional Data2D foo2d = 3;
    
      optional Data6D foo6d = 4;
    }
    
    
    message AllFooData {
      repeated FooData foo_data = 1;
    }