The Crystal Programming Language Forum

[Screencast] Using typed method overloads in Crystal to simplify branching logic

While the screencast is recorded through the lens of a Lucky application, I hope this introduction to method overloading will be useful to anyone like me coming from the Ruby/Rails world where this kind of clean structure is a lot harder to achieve!

7 Likes

type branching logic is not a good idea, because you logic will be split into some context.

like erlang and elixir, it had to find right way when use guards.

This is highly subjective. In the following code, branching on type is fantastic:

class MySlackBot < Slack::Client
  def handle(msg : Slack::HelloMessage)
    # Handle connecting
  end

  def handle(msg : Slack::ChatMessage)
    # handle a new chat message
  end

  def handle(msg : Slack::FileShared)
    # handle a new file upload
  end
end
2 Likes

This is really great! I love that it shows a new thought process to how we lay out the front-end, but also the fact that this can really be applied to any Crystal code.

its fantastic when branching is not so logic.