Skip to main content

# Best practices - writing .proto files

- Writing proto files - best practices
  - Syntax
  - Working with messages
    - Large data sets
    - Self describing messages

# Writing proto files - best practices

- Use PascalCase (with an initial capital) for message names – for example, `SongServerRequest`
- Use lower_snake_case for field names (including oneof field and extension names) – for example, song_name.

Title

    message SongServerRequest {
      optional string song_name = 1;
    }

- If your field name contains a number, the number should appear after the letter instead of after the underscore. For example, use `song_name1` instead of `song_name_1`
- Use pluralized names for repeated fields.

Title

    repeated string keys = 1;
      ...
      repeated MyMessage accounts = 17;

- Use PascalCase (with an initial capital) for enum type names and CAPITALS_WITH_UNDERSCORES for value names:

Title

    enum FooBar {
      FOO_BAR_UNSPECIFIED = 0;
      FOO_BAR_FIRST_VALUE = 1;
      FOO_BAR_SECOND_VALUE = 2;
    }

- Each enum value should end with a semicolon, not a comma
- Prefer prefixing enum values instead of surrounding them in an enclosing message
- The zero value enum should have the suffix `UNSPECIFIED`, because a server or application that gets an unexpected enum value will mark the field as unset in the proto instance
- If your .proto defines an RPC service, you should use PascalCase (with an initial capital) for both the service name and any RPC method names:

## Syntax​

- first line of the file must be the syntax version. `syntax = "proto3";` otherwise the compiler will asume `proto2`
- field types can be scalar types, enumerations and composed of other message types

Message Fileds cand be :

- singular types

- optional

- repeated

- map

- The order of the fields has no implication, the only thing that matters is the numbering

## Working with messages​

### Large data sets​

As a general rule of thumb, if you are dealing in messages larger than a megabyte each, it may be time to consider an alternate strategy.

That said, Protocol Buffers are great for handling individual messages within a large data set. . Usually, large data sets are a collection of small pieces, where each small piece is structured data. Even though Protocol Buffers cannot handle the entire set at once, using Protocol Buffers to encode each piece greatly simplifies your problem: now all you need is to handle a set of byte strings rather than a set of structures.

### Self describing messages​

Protocol Buffers do not contain descriptions of their own types. Thus, given only a raw message without the corresponding .proto file defining its type, it is difficult to extract any useful data

### File locations​

Prefer not to put .proto files in the same directory as other language sources. Consider creating a subpackage proto for .proto files, under the root package for your project