nmcalabroso

nmcalabroso

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.

Showing Posts 1 to 7

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/

cpgo

cpgo

Maybe extract the call to PasswordManager.valid? to your schema?
This post explains how to implement a custom validation.

Edit: I think this stackoverflow answer demonstrates better how to use add_error.

nmcalabroso

nmcalabroso OP

Agreed. Maybe I just chose a poor example. But what I’m trying to get at is how do we validate and “return early” in elixir? Of course, we can’t. But what’s the idiomatic way for this scenario?

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 OP

Hi @michalmuskala,

Can you give an example for this? Apologies if this is considered spoon-feeding but I genuinely interested to know.

How would you emulate this the elixir-way?

validate_one
if true, continue else return error
validate_two
if true, continue else return error

nmcalabroso

nmcalabroso OP

Definitely reading this. Thanks a lot.

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
— All posts loaded —

Where Next? Top

Trending in Questions Top

RSP87
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
RemyXRenard
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
nseaSeb
Hello, I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
velrest
So my question is quite simple and i have found no conclusive answer on forum, google or AI. Should we use :erlang.float for Integer to ...
New
samoloth
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
FlyingNoodle
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
ryanwinchester
apply_graft/2 doesn’t rewrite an add_many sub-workflow’s deps on an add step. Grafted jobs cancel with “upstream job was deleted” Version...
New

Other Trending Topics Top

mudasobwa
I am happy to introduce the very α version of the new programming language compiled to BEAM. Welcome Cure. It has literally three kille...
New
marciok
Hi there! We created Gust: A task orchestrator inspired by Airflow. For those who have never heard about Aiflow, it’s a Python-based wor...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Dmk
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews