When static types make your code shorter

by
, posted

In short: I learned that static types, often derided for verbosity, can sometimes make your code shorter. In my case, I was able to delete some validation code because of the type annotations.

I was recently porting some code from Ruby to Crystal and was surprised by something: the Crystal code was shorter because it used static types. The Ruby code was 190 lines and the Crystal version was 163; about 15% shorter.

In the eternal debate between static and dynamic types, verbosity is often cited as superior in dynamic languages. You don’t have to specify types, so your code is shorter. I’ve definitely experienced this—I sometimes feel like I’m fighting the compiler, flooding my screen with noisy type gymnastics.

But my recent work showed me something I’d never seen before: it can sometimes make your code shorter because it can prevent states you don’t have to worry about.

In the original Ruby version of this code, you could specify a minimum length. It has to be an integer between 0 and 255. Here’s a simplified snippet of the Ruby code1:

# ...

def initialize(min_length)
  unless min_length.is_a?(Integer) && min_length >= 0 && min_length <= 255
    raise "Minimum length has to be between 0 and 255"
  end

  @min_length = min_length
end

# ...

As you can see, the Ruby version validates that the argument is an integer between 0 and 255. This is necessary because a Ruby programmer could pass anything—a string, an invalid number, and so on.

This code could be completely omitted in the Crystal version because we can make invalid arguments impossible. By specifying the argument type as an UInt8, callers can’t mess this up, so we don’t need to validate.

Here’s what the Crystal looks like2:

# ...

def initialize(min_length : UInt8)
  @min_length = min_length
end

# ...

As you can see, all the validation code is gone! All I had to do was specify the argument’s type.

I was able to do this a few more times during my porting work; it felt good to delete a bunch of code.

My main takeaway was this: static typing gets a bad reputation for being verbose. That’s sometimes true! But sometimes, a static type system wins because it can prevent a hydra of impossible states.


  1. Check out the full version here. ↩︎

  2. Check out the full code in the Sqids Crystal repository↩︎