Johnny Butler

April 24, 2021

Ruby & Static Typing

Exposing myself to solidity & truffle.js recently I was reintroduced to static typing. Static typing generally consists of stating what the data type of a variable/attribute will be before assigning it a value. If that value ever changes it’s data type unexpectedly it will raise an error. Compiling your code can highlight such instances so can be fixed before publishing. Compiled code is much faster than non compiled code. These are two of the main benefits of static typing. 

One of the main attractions to Ruby & Rails in general is its easy to get to grips with less barriers to entry. A variable/attribute can be any data type at anytime throughout the lifecycle of an application. This flexibility is very appealing especially in the early stages of development. You may not know the exacts and might be feeling your way to more concrete examples. As an application matures/grows however this can lead to problems when variables/attributes unexpectedly change data type and cause errors. Everyone has had to deal with the unexpected nil error or a decimal value mutating into a string at some point.

In Ruby 3 static typing will be there and you can be included if you want, this is a step in the right direction. Having it there as an option will hopefully make more programmers aware of static typing and what the pros/cons are. Even though I don’t use static typing in Ruby I am conscious that the data type of a variable/attribute shouldn’t change unexpectedly during execution. Activerecord does a good job mapping a database data type into its ruby counterpart so you don’t even have to think about it. All the programmer has to do is control if/when and when it might change. 

Sorbet 

Stripe have introduced a library called Sorbet that allows static typing and is used in their Ruby/Rails applications. I can definitely see the benefits of this for a large team working on large applications. Shopify & Github are also using Sorbet so clearly adding huge benefits to large scale projects with many developers. 

Crystal

Crystal is a language derived from Ruby and has static typing enforced. Once compiled initial benchmarking has indicated it’s faster than C.

Conclusion

I am not advocating that static typing should be enforced, Ruby has the right approach by making it optional. Raising awareness of static typing is key however as anyone that takes it into consideration should produce better quality code. I see a lot of bugs that would have been stopped if static typing was enforced.