Shopify2023-10-18Explainer
Writing Better, Type-safe Code with Sorbet
Summary
Ruby repositories can hide unsafe method calls and ambiguous data shapes when types are inferred from variable names alone. Sorbet static type checking addresses these risks with method signatures, typed structs, enums, and interfaces. It can flag a potentially nil return before a chained call, distinguish database output fields from input fields, and enforce contracts for synchronous and asynchronous indexers in a dependency-injected hexagonal structure. The article also describes Sorbet’s gradual typing, including five strictness levels and namespace-by-namespace adoption using the minimum typed level of true. The stated conclusion is that enforced type safety catches errors unit tests may miss and helps prevent unsafe code from reaching production.
Context
Ruby code that relies on inferred variable names and untyped hashes can obscure method return types, optional fields, enum constraints, and the differences between data variants. The repository’s dependency-injected hexagonal structure also requires explicit contracts between components.
Approach / What changed
The team adopted Sorbet static type checking through method signatures, typed Sorbet structs, enums, interfaces, and gradual file-by-file typing. Adoption proceeds namespace by namespace, upgrading files to at least the true level when related work requires them; GraphQL is also used for type contracts between services.
Takeaways
Sorbet can reject a chained call when a method signature permits nil, reducing reliance on trivial unit tests for every return case.
Typed structs distinguish input ads from database-returned ads, while enums constrain state values and make nullable fields explicit.
Sorbet interfaces require synchronous and asynchronous indexers to implement the expected method and return types, supporting dependency injection and polymorphism.
Source and freshness
- Source
- shopify.engineering
- Published
- Added to Yomu
- Last updated
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.