Elixir has really changed the way we think about programming. Instead of thinking about objects and calling methods that change their state, we now think more in terms of functions that transform data.
An HTTP web server is a great example of the Elixir way of doing things. At a high level, a web server takes a request and, through a series of transformations, produces a response. In this video from our new Developing With Elixir course, we set up a pipeline for those high-level transformations so we have a basic outline of our program.
The program doesn't do anything interesting yet—the functions simply return hard-coded data. But we like to start this way as it helps us think through the program as a series of data transformations.
In the video, we started by sequencing the three transformation functions in a traditional style using intermediate variables:
def handle(request) do conv = parse(request) conv = route(conv) format_response(conv) end
You could condense this a bit and remove the temporary variables by nesting the function calls like so:
But this is difficult to read since the functions resolve from the inside out. Using the pipe operator lets us unwind these nested calls by chaining the functions together in a more readable style:
request |> parse |> route |> format_response
It transforms the request by piping the result of each function into the next function. Here's a fun fact: At compile time this code is transformed to the nested call version.
If you're making the change from OO programming to functional programming, one of the big differences is learning to think in terms of transforming data. You'll see a lot more examples of this throughout the course.
In the next several modules, we'll implement each of these functions so that an appropriate response is returned for different types of requests.
Build a complete Elixir app from scratch!
Save yourself time, frustration, and the perils of coding by coincidence by learning all the essentials of developing Elixir apps upfront in our Developing With Elixir course.