rob-brown / MonadEx

Upgrade your pipelines with monads.
MIT License
309 stars 13 forks source link

MonadEx over "Try & Rescue" #4

Closed henry-hz closed 8 years ago

henry-hz commented 8 years ago

Hi Daniel,

many thanks for the fantastic Monadex lib, I finally feel that I understood the monads abstractions, and how important they are to reduce our codebase. But I still have some questions about the practical use of MonadEx. Let me ask you, for the "Result" monad, the solution below, to deal with errors during the pipe execution, lacks something to drive me to use MonadEx, or it's enough ? What would be the advantage to use MonadEx over the solution below ?

thanks

Henry

try do
  opts
  |> Keyword.fetch!(:source_file)
  |> File.read!
rescue
  e in KeyError -> IO.puts "missing :source_file option"
  e in File.Error -> IO.puts "unable to read source file"
end
rob-brown commented 8 years ago

Largely it comes down to personal preference. Monads and exceptions act very similarly. The new with syntax is also very similar.

Generally in Elixir (and Erlang) we don't use exceptions. The preferred way is to use pattern matching with the with syntax. Consequently, with removes a lot of the need for Maybe and Result monads.

The advantage that monads have is the ability to call map, bind, apply, etc on them. Though your mileage may vary depending on who else is working on the same project. Not everyone is comfortable with monads (or functional programming).

For me the biggest benefit of monads is that all my functions receive and return the same type of value. This makes re-arranging and composing functions very easy. It's not easy to compose functions when one returns {:ok, string} and the next function just needs string. Again, with fixes a lot of that (or just using ! and catch the exceptions).

All three approaches are useful. In some cases one will be cleaner or easier than the others. I like to know all the alternatives and use whatever fits best.