MeerKatDev
How do you return your ok tuples?
I was wondering what Elixir developers think about this: how to treat piping into an ok_tuple? I have no idea if there was a similar question, I searched but I could found only posts on how to treat ok/error tuples cases.
I mean, between these, which ones would you prefer? I guess they’re all valid to a certain extent, just curious about different points of views ![]()
-
{ :ok, conn |> assign(:attr_one, :value_one) |> assign(:attr_two, :value_two) |> assign(:attr_three, :value_three) } -
{ :ok, assign( conn, attr_one: :value_one, attr_two: :value_two, attr_three: :value_three ) } -
conn |> assign(:attr_one, :value_one) |> assign(:attr_two, :value_two) |> assign(:attr_three, :value_three) |> (&{:ok, &1}).()
or there might be something different better, can’t think at any other right now.
Most Liked
benwilson512
When constructing literals (like tuples, but also lists and maps) I try to always have the elements of that literal just be simple variables, or other literals. That is to say, when reading the literal, you can just focus on its structure, and you don’t need to also read various function calls along the way. eg:
I favor
conn =
{:ok, conn}
And stuff like:
comments =
posts = fetch_posts(...)
users = posts |> Enum.map(& &1.author)
%{
users: users,
posts: posts,
comments: comments
}
If you mix a bunch of function calls inside the literal you have to read it sort of inside out.
kartheek
I prefer readability over everything else:
conn =
conn
|> assign(:attr_one, :value_one)
|> assign(:attr_two, :value_two)
|> assign(:attr_three, :value_three)
{:ok, conn}
I tend to keep creation of tuples, maps, etc as simple as possible. Someone else who is going to read and maintain code I have written should not have any cognitive overhead.
gregvaughn
I typically agree with @benwilson512 's preference there. However since Elixir 1.12 there’s a new option that I haven’t had much chance to use, so I haven’t fully formed an opinion on it.
conn
|> assign(attr_one: :value_one, attr_two: :value_two, attr_three: :value_three)
|> then(&{:ok, &1})
I prefer the single call to assign with a keyword list, and I prefer then to the anonymous function syntax used in option 3.







