Skip to content

Return default values for unset required fields instead of throwing#5

Merged
merlimat merged 1 commit intostreamnative:masterfrom
merlimat:fix-required-field-defaults
May 8, 2026
Merged

Return default values for unset required fields instead of throwing#5
merlimat merged 1 commit intostreamnative:masterfrom
merlimat:fix-required-field-defaults

Conversation

@merlimat
Copy link
Copy Markdown
Collaborator

@merlimat merlimat commented May 8, 2026

Summary

  • Required field getters in proto2 now return type-appropriate defaults (0, false, "", empty bytes, valueOf(0), lazily-created empty message) instead of throwing IllegalStateException. This matches protobuf-java, where unset required fields read back as defaults and validation only happens at build/serialize/parse boundaries.
  • writeTo() and parseFrom() still call checkRequiredFields() and throw IllegalStateException when a required field is missing — only the per-field accessors changed.
  • Follows the same fix applied to optional fields in Return default values for unset optional fields instead of throwing #2.

Test plan

  • Added RequiredTest.testUnsetRequiredReturnsDefault asserting parity with protobuf-java for the getter, serialization, and deserialization paths
  • mvn -pl tests test — all 259 tests pass

Previously, accessing an unset required field (proto2) would throw
IllegalStateException. This breaks compatibility with standard Protobuf,
which returns type-appropriate default values for any unset field
regardless of whether it is required or optional. Required-field
validation in Protobuf happens at build/serialize/parse time, not on
every accessor call.

Required field getters now return the same defaults as optional fields:
- Numbers: 0 / 0L / 0.0 / 0.0f
- Booleans: false
- Strings: ""
- Bytes: empty byte[] / empty ByteBuf
- Enums: valueOf(0)
- Messages: lazily-created empty instance

writeTo() and parseFrom() still call checkRequiredFields() and throw
IllegalStateException when a required field is missing, matching the
existing behavior at the message boundary.
@merlimat merlimat merged commit 11d8630 into streamnative:master May 8, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant