jtomschroeder/crystalline — pull request #1 by asterite (2014-10-31 12:24:55+00:00)
Title: More idiomatic ways of handling nil

Hi!

I saw lots of `nil?` and `not_nil!` in your code and I thought I'd send you this pull request with more idiomatic ways of handling nil.

Instead of:

```ruby
unless some_value.nil?
some_value.not_nil!.some_method
end
```

You can do:

```ruby
if some_value
some_value.some_method
end
```

More about this [here](http://crystal-lang.org/docs/syntax_and_semantics/if_var.html). As it says there, that doesn't work for instance variables so you have to assign them to a temporary variable (by now we are doing that all over the place: it's idiomatic and also efficient, as the nil check is done only once).

You can also use `try` if it's just a one liner:

```ruby
some_value.try &.some_method
```

The above is the same as:

```ruby
some_value.try { |v| v.some_method }
```

(so you can actually use `try` for more than one line, but I think using a `if` is clearer in those cases)

Don't be afraid of using blocks because of possible performance issues. I don't know about Ruby, but in Crystal, if a method doesn't captures a block (accesses it via it's name), then a closure is never generated and the call is always inlined. So this:

```ruby
10.times { puts 1 }
```

Is exactly the same as writing this:

```ruby
i = 0
while i < 10
puts 1
i += 1
end
```

When I say "exactly the same" I mean it: the compiler generates the same code in both cases (even when you compile without the `--release` flag).

Also, this:

```ruby
def foo(x)
return unless x

x.some_method
end
```
The compiler knows that if there's no `x` (`x` is *falsey*) then the method will return, so afterwards it knows that `x` can't be `nil`.

In general we try to avoid `not_nil!` unless there's no way the compiler can know we know a value is not nil (but we may be wrong ;)).