Type Safety

This document explains how Azu leverages Crystal's type system to catch errors at compile time rather than runtime.

The Problem with Dynamic Types

In dynamically typed frameworks, common errors only appear at runtime:

# Ruby/Rails - These errors happen at runtime
def create
  user = User.create(params[:user])
  render json: user.to_josn  # Typo not caught until runtime
end

You might deploy this code and only discover the bug when a user hits it.

Crystal's Static Typing

Crystal catches errors at compile time:

# This won't compile - typo caught immediately
user.to_josn  # Error: undefined method 'to_josn' for User

# Correct
user.to_json

Type-Safe Endpoints

Azu uses generics to enforce types:

The compiler ensures:

  • call returns UserResponse

  • All code paths return the correct type

  • The request object has the expected shape

What Happens If You Return Wrong Type

This error is caught at compile time, not after deployment.

Type-Safe Requests

Request contracts define expected input:

Benefits:

  • Clear documentation of expected input

  • Automatic parsing into correct types

  • Validation runs before your code

Accessing Request Data

Type-Safe Responses

Responses define output shape:

The compiler verifies:

  • All fields exist on User

  • Types are correct for JSON serialization

Type-Safe Parameters

Route parameters are always strings, but conversion is explicit:

Nil Safety

Crystal's nil-safety prevents null pointer errors:

Union Types

Handle multiple cases explicitly:

Generic Handlers

Create reusable, type-safe handlers:

Error Messages

Crystal's error messages help identify issues:

Trade-offs

Advantages

  • Catch bugs before deployment

  • Self-documenting code

  • Better IDE support

  • Refactoring confidence

Considerations

  • More upfront type declarations

  • Learning curve for dynamic language developers

  • Some patterns require more verbose code

Best Practices

  1. Be explicit about types

  2. Use meaningful type aliases

  3. Handle all cases

  4. Leverage union types for flexibility

See Also

Last updated

Was this helpful?