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:
- Hex.pm page: https://hex.pm/packages/std_result
- Documentation: https://hexdocs.pm/std_result
- Source code: https://github.com/ImNotAVirus/std_result
Most Liked
sasajuric
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
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. ![]()
@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.
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(orto_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
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.
Popular in Announcing
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #code-sync
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








