benhoven

benhoven

Different/simple ways to implement some_function() and some_function!() that raises exception

Hi Everybody ;-),

Based on my understanding the proper Elixir way is to implement functions that return :ok or :error instead of raise exception. And then if there is a need you can implement a function with the same name + exclamation mark that you can use when you’re sure that the code should work and therefore if it doesn’t you want raise in that function to terminate the app (or process).

Recently I found myself in situation where I wanted to implement a lot of functions without and with exclamation mark.

Example:

defmodule MySuperCool.BigModule do
  def do_something(some_input, some_number) when is_map(some_input) and is_integer(some_number) do
    # stupid example
    case some_input do
      %{valid: true} -> {:ok, some_number}
      _ -> :error
    end
  end

  def do_something!(some_input, some_number) when is_map(some_input) and is_integer(some_number) do
    case do_something(some_input, some_number) do
      :error -> raise ArithmeticError
      {:ok, out} -> out
    end
  end

I’m looking at the code realizing that I have a lot of functions like do_something! with case that returns / raise exception. In other words I’m repeating the same code again and again…

So I tried to create a helper and rewrite it like this:

defmodule MySuperCool.SomeHelpers do
  def raise_error_or_return_value_in_tuple(result, exception \\ UndefinedFunctionError, exception_opts \\ [])
      when is_atom(exception) and is_list(exception_opts) do
    case result do
      :error -> raise exception, exception_opts
      {:ok, value} -> value
    end
  end
end

defmodule MySuperCool.BigModule do
  import MySuperCool.SomeHelpers, only: [raise_error_or_return_value_in_tuple: 3]

  # same as above

  def do_something!(some_input, some_number) when is_map(some_input) and is_integer(some_number) do
    some_input
    |> do_something(some_number)
    |> raise_error_or_return_value_in_tuple(ArithmeticError)
  end
end

And as you can see I “simplified” 4 lines of case statement into 3 lines some_input |> function |> raise_or_return.

In my view the simplification doesn’t really simplify it…

Could you please tell me should I just continue with case statements in every question mark function?

Thank you.

Kind regards,

Ben

Marked As Solved

wolf4earth

wolf4earth

I think there is some interesting thought here. I certainly have written my fair share of bang-functions using the case-approach. And while I have no objection in particular against it (it’s only 4 lines after all) this could be a nice little macro exercise.

Disclaimer: As @al2o3cr writes below, using this is probably not a good idea, as it’s a major layer of indirection which will make your codebase harder to reason about. Nevertheless it’s an interesting use-case for macros, so consider this an educational example rather than a production ready one.

defmodule Boom do
  defmacro defbang({name, _meta, args}, raising: error) do
    quote do
      def unquote(:"#{name}!")(unquote_splicing(args)) do
        case apply(__MODULE__, unquote(name), unquote(args)) do
          {:ok, value} -> value
          {:error, reason} -> raise unquote(error), reason
        end
      end
    end
  end
end

Which you could then use like this:

defmodule Test do
  import Boom

  def test(nil), do: {:error, "is nil"}
  def test(val), do: {:ok, val}

  defbang test(num), raising: ArgumentError
end

Test.test(42)
#=> {:ok, 42}

Test.test("test")
#=> {:ok, "test"}

Test.test(nil)
#=> {:error, "is nil"}

Test.test!(42)
#=> 42

Test.test!("test")
#=> "test"

Test.test!(nil)
#=> ** (ArgumentError) is nil

As mentioned before, I’m not saying that this is a good idea - after all it’s a probably unnecessary layer of indirection - but it’s possible.

Also Liked

shanesveller

shanesveller

I don’t think I’ve seen it specifically mentioned when I skimmed the thread, but I typically write functions that can raise as very thin wrappers around the versions that return either ok-tuples or error-tuples. It just calls the non-raising version directly, then unwraps the okay tuple or raises on an error tuple. Exceptions generally don’t need all of the context an error tuple might include, so it’s rare that I need to have two parallel, standalone function bodies, which need better test scrutiny.

al2o3cr

al2o3cr

Couple thoughts on this:

  • it makes the definition of test! harder to find - for instance, simple searches for def test! won’t turn it up at all.
  • applying @doc and @spec to the generated function is possible but looks odd (since the name in @spec doesn’t appear explicitly in a def)
  • barring some advanced macro-fu, the data passed to raise has to be known at compile-time and so can’t include any information about the actual arguments that caused a failure
  • a future reader of this code will need to understand what the macro does to understand what test! does, versus reading four lines of straightforward Elixir
LostKobrakai

LostKobrakai

Those are exactly the reasons, why I feel this is a place for copy/paste or an editor macro and not a code level abstraction.

al2o3cr

al2o3cr

I don’t see a problem with that - it’s readable, and should be a familiar idiom for future readers.

A better question: are you sure you need this much API flexibility? Providing bang and non-bang functions is important for libraries, but carefully consider if your internal APIs could be more opinionated.

benhoven

benhoven

Thank you Bluejay, It’d have to be bang(do_something(input, number)), ArithmeticError or even bang(do_something(input, number)), KeyError, key: :my_key, term: "bla bla bla" with the exception and exception attributes as as optional arguments.

I’m still considering it… case is simple and explicit. bang() would be shorter but maybe it’s just unnecessary complexity.

The bang library is very interesting. At least I’ll take a look how it works inside.

Where Next?

Popular in Questions Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
mgjohns61585
Could someone help me? I'm making my first elixir program, number guessing game. I can't figure out how to convert the user's guess from ...
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
skosch
To my knowledge, put_in, Map.update etc. all have the one limitation of not automatically creating intermediate keys when needed (for exa...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
peerreynders
Manning 2016 Halloween weekend sale via Deal of the Day Friday, October 28 - Half off all MEAPs - code WM102816LT Saturday, October 29 ...
326 29600 154
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod -- where is this set? Thanks.
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
siddhant3030
Hi, I have to write a raw query for one of my project. But till now I have used ecto queries and don’t have much experience writing raw ...
New

We're in Beta

About us Mission Statement