nmcalabroso

nmcalabroso

What is the idiomatic way for input validations?

I’m new to elixir and functional programming, in general. I want to ask what’s the idiomatic way to validate our input parameters? Say I want to do this in my UserController.create.

Check if password is valid by PasswordManager.valid?/1
If not, render error
else, continue

This is what I’ve come up with:

defmodule MyApp.UserController do
  def create(conn, %{"data" => data}) do
    case PasswordManager.valid? user_attrs["password"] do
      {:ok, raw_password} ->
        # make changeset with hashed password
        case Repo.insert(changeset) do
          {:ok, user} ->
            # success
          {:error, invalid_changeset} ->
            # render failure  
      {:error, reason} ->
        render(conn, :errors, data: reason)
    end
  end
end

The issue here is the “ugly” nesting seems unnecessary. I’m looking for a “return early” statements but I guess elixir wants us to write pure functions as much as possible and utilize pattern matching accordingly. How do I refactor this?

Coming from python, I would do this:

def create(user_attrs):
  if not PasswordManager.is_valid(user_attrs['password']):
    # display error
    return
  
  # continue

But what’s the best practice in elixir?

Feel free to do some nitpicks to my code so I can improve writing in this language.

Also, please do note that I’m asking this as a generic question. I hope you don’t dwell too much with the password validation as an example. Thank you.

Marked As Solved

NobbZ

NobbZ

Nope, I think its meant like this:

with {:ok, data} <- validate_one(data),
     {:ok, data} <- validate_two(data) do
  {:ok, data}
else
  {:error, reason} -> {:error, reason}
end

Also Liked

wmnnd

wmnnd

Hello @nmcalabroso,

in Elixir and other functional languages, you cannot »return early« as you would do in Python or Ruby.
In your particular case, you could use the with keyword in order to avoid nesting and chain pattern-matched conditions together:

with {:ok, raw_password} <- PasswordManager.valid?(user_attrs["password"]),
     {:ok, changeset} <- create_changeset(user_attrs, raw_password),
     {:ok, user} <- Repo.insert(changeset) do
     #whatever you want to do if everything went okay
else
  {:error, reason} -> #whatever you want to do if there was an {:error, reason} tuple
end

You can read more about the with keyword in the Elixir Getting Started Guide: http://elixir-lang.org/getting-started/mix-otp/docs-tests-and-with.html#with

And here is a nice blog article about the with keyword and what’s called »Railway-oriented programming« in the F# world: http://www.scottmessinger.com/2016/03/25/railway-development-in-elixir-using-with/

michalmuskala

michalmuskala

I would say the most natural way of emulating “early return” would be to split the logic into multiple functions each one returning or continuing to the next one. The with construct is kind of a “get out of jail free card” - it allows you to encode those patterns less verbosely in a single expression. I’d say that’s the most “common” way to do this.

In case of ecto, the most idiomatic way of doing validations is to use, as mentioned, changesets.

nmcalabroso

nmcalabroso

Definitely reading this. Thanks a lot.

Where Next?

Popular in Questions Top

srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
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
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
belgoros
I’m not a pro in using Regex and can’t figure out why the following behaviour happens, especially if we take into account the difference ...
New
Fl4m3Ph03n1x
About me? ( if you have nothing better to do than reading about some random guy in the internet :stuck_out_tongue: ) Hello all, this is ...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New

Other popular topics Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
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
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID&lt;0.412.0&gt; terminating ** (Postgrex.Error) FATAL...
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
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New

We're in Beta

About us Mission Statement