Is it OK to rely on returned data during series of pipes?

I was just reading a post on the forum about OO vs FP. I’m only a few months into FP from a good 5-year in not-even-OO Ruby/Rails. One argument I’ve seen against OO is the inherent mutation of data.

But I’ve been doing this quite often:

myResult
|> returnTransformedData
|> doSomethingWithTransformedData
|> logTransformedData

And so the later functions are relying on the returns from the earlier functions. But if I pass the same data into each function, then I’m repeating the transformation (unless I stored its state). Having trouble reconciling this dependence on these returns with data mutation in OO, and unsure if I’m carrying over a bad habit.

Piping is basically like assembling your own LEGO model by using existing blocks (think being able to build a space ship, a train, and a boat all by reaching in the same crate of blocks). There is no repeat of transformation here. One function finishes and passes its result as input for the next.

Repeated transformations are a problem in any language. If you have an expensive computation you need only for a single function but you will use it 2 or more times in that function, then just store it in a variable and reuse? Not sure I understand your question and concern here.

Piping does not do mutation. You simply get the output of function 1 and pass it as the first argument to function 2, then the result of function 2 gets fed as first parameter to function 3, etc.

1 Like

@BitGonzo: Depends on scenarios. Some time you can’t simply trust data passed in pipe. A good example here are web scrapers where some data part of structs can simply not exists, because they have been not specified in system.

To handle such cases you can use an OK library for that. Here is an documentation of lhs ~> rhs operator:

Pipeline version of map/2.

Examples
iex> {:ok, 5} ~> Integer.to_string
{:ok, "5"}

iex> {:error, :zero_division_error} ~> Integer.to_string
{:error, :zero_division_error}

iex> {:ok, "a,b"} ~> String.split(",")
{:ok, ["a", "b"]}

Thanks for the responses.

@dimitarvp I should clarify - I meant to edit out that transformation. I am certainly not assuming the data is being mutated through those function returns. I understand the depth of the immutability in that sense. It is more the reliance on the overall transforming of that flow of data (seems quite abstract at this point) as another form of state-reliance.

I was just curios to see the general idea about this.

@Eiji great point! Similar to the reason I was asking (working on something similar to scraping).