ImNotAVirus

ImNotAVirus

std_result - A way to standardize function returns

Hi everyone,

Published a new library: StdResult!

StdResult is a library designed to standardize function returns.
Highly inspired by Rust’s std::result, this library provides a way of simplifying the management of :ok and :error tuples by providing functions for manipulating them.

The problem:
One problem I come across quite often is the lack of consistency between certain functions. In the same module, some functions will sometimes return :ok while others will return {:ok, result} and others just result. The same goes for errors. It can quickly become complicated to manipulate these results.

That’s where StdResult comes in.

Usage:
Here is a simple example: let’s say we need to retrieve an environment variable, convert it to an integer and check that it’s positive. Our function should return {:ok, value} or {:error, reason}.

Here’s an example of what it might look like with StdResult.

import StdResult

System.fetch_env("PORT")
# This will transform `:error` into a `:error` tuple
|> normalize_result()
# If there is an error, explicit the message
|> or_result(err("PORT env required"))
# If no error, parse the string as an integer
# We could also have used `Integer.parse/1` but for simplicity's sake we won't.
|> map(&String.to_integer/1)
# Test if the number is positive
|> and_then(&(if &1 >= 0, do: ok(&1), else: err("PORT must be a positive number, got: #{&1}")))

# The result will be either:
# - `{:ok, port}`
# - `{:error, "PORT env required"}`
# - `{:error, "PORT must be a positive number, got: <value>"}`

Check out the documentation for more details on existing functions.
Any issues, suggestions or contributions are welcome.
Cheers


Links:

Most Liked

sasajuric

sasajuric

Author of Elixir In Action

To reduce the amount of function splits and these micro-functions, I use a helper function called validate, which transforms a boolean into :ok | {:error, reason}:

def validate(true, _reason), do: :ok
def validate(false, reason), do: {:error, reason}

And now you can write

with :ok <- validate(User.exists?(updated_user.id), :not_found), ...

It doesn’t solve all the problems you mention, but it can often help avoiding micro-functions and keep the logic in a single place, for the price of a small function whose semantics are easy to grasp. I’ve introduced it to multiple teams and programmers with different experience levels, and it worked quite well, especially in combination with Repo.transact mentioned in another thread.

dimitarvp

dimitarvp

I think you all are being too harsh on OP here, he spotted a problem and offered his take on it. Let the guy live, he doesn’t deserve the death sentence you are giving him. :smiley:

@ImNotAVirus I do understand the motivation for your library but I’d be personally against using it in its current form because to me it introduces ambiguity and conditions in pipes, and overall just increases code size without offering clarity of intent in return. Furthermore, the problem statement is to me minor; I never found it problematic to have my guard up and properly catch singular :ok / :error atoms. :person_shrugging: It’s part of the job, plus we have Dialyzer, plus we have “Go to definition” and “Go back” in our IDEs, so… I don’t know. The problem does not seem major to me.

IMO if you want to push the library ahead then you should aim for ultra mega hyper terseness; not just the to_result renaming that you said you’ll adopt, but also you should have only 2-3 functions in the library that do practically everything that your current separate functions are doing right now.

My points:

  • You want to call functions that are not guaranteed to return proper {:ok, value} / {:error, reason} tuples? Use a singular library function e.g. ok_err (or to_result) that absolutely always will return the proper tuple regardless of what is fed to it.

  • You want to have custom validation / error reporting functionality? Well, IMO that is another library. Your post (and likely the library as well) seems to be mixing concerns.

  • The Elixir community usually resists usage of such libraries because (a) most teams feel that doing what the library does is trivial enough and (b) nobody wants to adopt new idioms without a very clear value proposition.

cmo

cmo

Another solution is to use your editor to inspect the function (hover, keyboard shortcut, etc) to see the spec. This doesn’t introduce cognitive load, you learn the standard library, you don’t pay a performance penalty and are more likely to write idiomatic code.

It is convention that functions/macros ending with a ! raise exceptions.

Where Next?

Popular in Announcing Top

asiniy
Hey there! I wrote a download elixir package which does exactly what its name about - an easy way to download files. I saw solutions ab...
New
ostinelli
Let’s write a database! Well not really, but I think it’s a little sad that there doesn’t seem to be a simple in-memory distributed KV da...
New
josevalim
Yes, yet another parser combinator library! Most of the parser combinators in the ecosystem are either compile-time, often using AST tra...
159 19228 141
New
deadtrickster
I’ve just released stable versions of my Prometheus Elixir libs: Elixir client [docs]; Ecto collector [docs]; Plugs instrumenter/Export...
New
restlessronin
The repo is at GitHub - cyberchitta/openai_ex: Community maintained Elixir library for OpenAI API · GitHub. Docs are at OpenaiEx User Gu...
152 10167 134
New
Crowdhailer
Raxx is an alternative to Plug and is inspired by projects such as Rack(Ruby) and Ring(Clojure). 1.0-rc.1 is now available. To use it re...
New
ahamez
Hi everyone, I’ve been working on this protobuf library for 3 years. We use it in the company I work for, EasyMile, to communicate with ...
New
sabiwara
Dune is a sandbox for Elixir and aims to safely evaluate user-provided code. You can try it out using this basic Elixir playground made ...
New
Hal9000
Here is my first stab at this. README pasted below. https://github.com/Hal9000/elixir_random Comments and critiques are welcome. Thank...
New
achempion
Hi, I would like to tell about my initiative to further maintain and develop Waffle project which is the fork of Arc library. The progre...
New

Other popular topics Top

aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
Darmani72
If I have a post route which an argument: post /my_post_route/:my_param1, MyController.my_post_handler How would get the post params ...
New
AstonJ
Posting this to see if we can make things easier for people to get into Neovim. If you use Neovim and have a favourite distro please let ...
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
Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
AstonJ
Please see the new poll here: Which code editor or IDE do you use? (Poll) (2022 Edition) It’s been a while since we first asked this, I...
208 31142 143
New

We're in Beta

About us Mission Statement