Gilou06
Conditional piping part of the language?
Hello,
I keep using a paradigme using a homemade function to make my life easier when piping.
I wonder if there is a better way to achieve the same result, maybe something already part of Elixir language.
Instead of writing a tailored maybe_dothat() function, I prefer a generic maybe_do() wrap function around a do_that() function.
Here is the may_be/1 wrapper.
def maybe_do(pipe_value, condition, function)
when is_boolean(condition) and is_function(function) do
if condition do
function.(pipe_value)
else
pipe_value
end
end
Let’s say I want to always call do_this/1 on a socket and do_that/1 but only if my_bool is true, else socket rest unchanged.
I write it this way:
socket
|> maybe_do(my_bool, &do_this/1)
|> do_that()
Your insights are welcome.
Jean-yves ![]()
Most Liked
dimitarvp
As the other poster said, tap and then cover a lot of needs, and also yeah if it’s more convenient for you to use your own function then please don’t feel bad about it! It’s very normal.
People use their own functions a lot when you need to go through a series of validations, for example. It’s expected to do it like that in many teams even.
dimitarvp
An alternative implementation:
def maybe_do(value, true, func) when is_function(func, 1), do: func.(value)
def maybe_do(value, _, _), do: value
sodapopcan
It’s very hard to tell without seeing your exact code, but if you’re feeling it’s a code smell it’s possible that you are trying to force a pipeline when it is not needed. Once you start threading tuples like {event, socket} through a pipeline where only one function cares about event, you’re hiding details. It makes it harder in the future to read the pipeline at a glance without looking at the implementation of each function. Of course if it’s a pattern that appears everywhere it’s not such a big deal, but generally pipelines are best when they operate on a single immutable data structure. YMMV, of course.
cloudytoday
You can do the same with case:
value
|> case do
x when my_condition -> f.(x)
x -> x
Alternatively you can write a macro that supports holes, lets say you call it p:
value
|> (p if my_condition, do: f.(_) else: _)
Doesn’t have to be exactly like this ofc, you can define it to be whatever you like the most. Just giving an example here. I actually have a bunch of these in my helpers libs. Edit: or, even better, you can also extend the pipe itself with this macro.
derek-zhou
In my opinion, over use of then is a code smell; your maybe_do function is not.







