mario_sunny
mario_sunny

Reputation: 1432

Protocol buffers: read only fields?

Is it possible to mark fields as read only in a .proto file such that when the code is generated, these fields do not have setters?

Upvotes: 5

Views: 4779

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063864

Ultimately, I think the answer here will be "no". There's a good basic guidance rule that applies to DTOs:

  • DTOs should generally be as simple as possible to convey the data for serialization in a manner well-suited to the specific serializer.
  • if that basic model is sufficient for you to work with above that layer, then fine
  • but if not: do not fight the serializer; instead, create a separate domain model above the DTO layer, and simply map between the two models before serialization or after deserialization

Or put another way: the fact that the generator doesn't want to expose read-only members is irrelevant, because if you need something exotic, you shouldn't be using the generated type outside of the code that directly touches serialization. So: in your domain type that mirrors the DTO: make it read-only there.

As for why read-only fields aren't usually a thing in serialization tools: you presumably want to be able to give it a value. Serialization tools usually want to be able to write everything they can read, and read everything they can write.


Minor note for completeness since you mention C#: if you are using a code-first approach with protobuf-net, it'll work fine with {get;}-only auto-props, and with {get;}-only manual props if all public members trivially map to an obvious constructor.

Upvotes: 3

Related Questions