Sitemap
Better Programming

Advice for programmers.

Railway Oriented Programming

--

Press enter or click to view image in full size
Image generated by Midjourney

This pattern is one of the useful patterns for functional programming languages, especially for the Elixir programming language, because of pattern matching. You can read more about it in the articles below:

  1. Railway Oriented Programming in Elixir with Pattern Matching on Function Level and Pipelining
  2. Elixir’s with statement and Railway Oriented Programming

This article will show you how clear and easy it is to solve difficult issues and write code that is really simple to read and maintain.

We continue to develop our example application, as seen in the following link: https://github.com/sergey-chechaev/example_app, to show you the benefits of this pattern and how it works.

Let’s imagine an external service sends some data to our endpoint, and we need to save data to different data tables, send an email and run a background job. This time, create a service that can do all the above using the railway approach.

  1. Create the folder services and a payment_executor.ex file in which to put this logic:
mkdir lib/services/ && touch lib/services/payment_executor.ex

2. Write a module doc explaining what this service does.

defmodule Services.PaymentExecutor do
@moduledoc """
This service creates the payment, an invoice and
sends an email to the manager and calculates statistics
"""
end

3. Write a struct that helps to implement the railway pattern. This struct must contain two required attributes: valid? and error.

defmodule Services.PaymentExecutor do
@moduledoc """
This service creates the payment, an invoice and
sends an email to the manager and calculates statistics
"""

defstruct payment_params: nil,
payment: nil,
invoice: nil,
valid?: true,
error: nil
end

Defstruct helps to provide compile-time checks, default values, and it also provides specifications to understand the data this service works with. Attributes payment_params, payment andinvoice are needed to store data for the functions described below.

Define this module as a service, so a function call is used for the entry point. This function must consist of functions that solve specific tasks. Their names are explanatory and help to read the function call as a specification:

defmodule Services.PaymentExecutor do
@moduledoc """
This service creates the payment, an invoice and
sends an email to the manager and calculates statistics
"""

defstruct payment_params: nil,
payment: nil,
invoice: nil,
valid?: true,
error: nil

def call(payment_params) do
payment_params
|> build_struct()
|> create_payment()
|> create_invoice()
|> send_email()
|> execute_statistic_worker()
|> transform_result()
end
end

The function call can be read as a specification.

  • build_struct — fill in the structure of the module Services.PaymentExecutor
  • create_payment — insert data to the payment’s data table
  • create_invoice –insert data to the invoice’s data table
  • send_email — send an email to the manager
  • execute_statistic_worker — start background job to calculate some payment statistics
  • transform_result — the last function that returns results

All that remains is to implement these functions by using the Railway Pattern.

4. Create the schema Invoice for the same context Payments

mix phx.gen.json Payments Invoice invoices from:string bill_to:string amount:decimal tax:decimal

We add the Schema Invoice to show how we can use this pattern for solving issues when we need to insert data into many tables. In OOP languages, we use Pattern Service Object or Form Object. For functional programming, languages like Elixir and Railway-Oriented Programming have common principles.

5. The best practice in the Elixir community is to create good documentation and specifications for the module.

Get Sergey Chechaev’s stories in your inbox

Join Medium for free to get updates from this writer.

See the following example:

@type payment_executor_struct_t :: %__MODULE__{}
@spec call(
payment_params ::
Map.t(
sum: float(),
bonus: float(),
tax: float(),
operation_type: Enum.values(Payment, :operation_type),
pay_period_from: UtcDate.t(),
pay_period_to: UtcDate.t()
)
) ::
Tuple.t(:error, Ecto.Changeset.t())
| Tuple.t(:ok, payment_executor_struct_t())
  • @type payment_executor_struct_t — define custom types helps communicate the intention of your code and increase its readability. Describing the module struct itself helps to understand what the module is to return.
  • @spec call() — define function specification indicates what external parameters look like and their type.

6. Add all necessary functions. All the functions listed below are private. Since they are hidden for execution, it is indicated that only the call function needs to be performed.

 defp build_struct(payment_params) do
%__MODULE__{payment_params: payment_params}
end
  • build_struct — this function needs to prepare initial data and set it to defstruct. This entry point can be used for adding extra data to the struct or manipulating data.
defp create_payment(%__MODULE__{valid?: false} = struct), do: struct

defp create_payment(%__MODULE__{payment_params: payment_params} = struct) do
case Payments.create_payment(payment_params) do
{:ok, %Payment{} = payment} ->
%__MODULE__{struct | payment: payment}

{:error, error} ->
%__MODULE__{
struct
| valid?: false,
error: {:create_payment, "can't create Payment #{inspect(error)}"}
}
end
end
  • create_payment — the first function that illustrates the action of the principle of the railway pattern. The beauty of pattern matching is revealed here in full. If the value of the attribute valid? is false, this means we get red railway, and we return struct without any business logic execution.
    Conversely, if the value of the attribute valid? is true, this means that we get a green railway, and the business logic will be executed. Inside this function for the green railway, we create Payment and store the result in Module struct. If we can’t create Payment , for example, because of validation, we set the attribute valid? to false and the next function produces a red railway match.
defp create_invoice(%__MODULE__{valid?: false} = struct), do: struct

defp create_invoice(%__MODULE__{payment: %{sum: amount, tax: tax}} = struct) do
invoice_params = %{
amount: amount,
tax: tax,
from: "example app",
bill_to: "other example app"
}

case Payments.create_invoice(invoice_params) do
{:ok, %Invoice{} = invoice} ->
struct

{:error, error} ->
%__MODULE__{
struct
| valid?: false,
error: {:create_invoice, "can't create Invoice #{inspect(error)}"}
}
end
end
  • create_invoice — is similar to the create_payment and has the same pattern matching for the red and green paths. Inside this function, we create an invoice and store data to struct or set the attribute valid? to false and the next function produces a red railway path.
  defp send_email(%__MODULE__{valid?: false} = struct), do: struct

defp send_email(struct) do
IO.puts("Execute the worker to send an email to the manager")
struct
end

defp execute_statistic_worker(%__MODULE__{valid?: false} = struct), do: struct

defp execute_statistic_worker(struct) do
IO.puts("Execute the worker to calculate statistics")
struct
end
  • send_email, execute_statistic_worker — this function emulates sending an email to someone and executes worker. In other words, it starts the background job. These functions have the same pattern-matching principle to produce red and green paths.
 defp transform_result(%__MODULE__{valid?: false, error: error} = struct) do
Logger.error(inspect(error))
{:error, struct}
end

defp transform_result(struct) do
{:ok, struct}
end
  • transform_result — this function, the last function in the pipeline, returns struct tuple {:ok, payment_executor_strucy} or {:error, payment_exacutor_struct}. It’s easy to use for matching red or green path in other services or controllers. Use Logger.error to catch errors in console or logger services if we get a red path. Logger.error helps to debug in the future. Sentry or other debugging services can also be used to send information.

7. Add this service to the Internal Controller.

defmodule ExampleAppWeb.Internal.PaymentController do
use ExampleAppWeb, :controller

alias ExampleApp.Payments.Payment
alias Params.Internal.Payment, as: PaymentParams
alias Services.PaymentExecutor

action_fallback ExampleAppWeb.FallbackController

def create(conn, payment_params) do
with {:ok, prepared_params} <- PaymentParams.prepare(:create, payment_params),
params <- Map.from_struct(prepared_params),
{:ok, %{payment: payment}} <- PaymentExecutor.call(params) do
conn
|> put_status(:created)
|> put_resp_header("location", Routes.payment_path(conn, :show, payment))
|> render(ExampleAppWeb.PaymentView, "show.json", payment: payment)
end
end
end

Replace the Payments module with PaymentExecuter and as a result, business logic is hidden from the controller to this service. An option is to add action_fallback ExampleAppWeb.FallbackController to handle errors, therefore creating a service that puts all errors into Ecto.Changeset struct.

8. To facilitate work with errors, add a new module Services.ErrorBuilder.

defmodule Services.ErrorBuilder do
@moduledoc """
Wrap error into Ecto.Changeset struct
"""

import Logger
alias Ecto.Changeset

def call(error, module) do
if Application.get_env(:pushsms, :env) != :test do
Logger.error(%{module: module, description: error})
end

call(error)
end

def call({key, message}),
do: %Changeset{types: Map.new([{:key, :string}])} |> Changeset.add_error(key, message)

def call(%Changeset{} = error), do: error
end

This service helps to work with errors in a familiar way because it wraps errors to Changeset.

The function transform_result in PaymentExecuter needs modifying like this:

defp transform_result(%__MODULE__{valid?: false, error: error}) do
{:error, ErrorBuilder.call(error, __MODULE__)}
end

defp transform_result(struct) do
{:ok, struct}
end

As a result, action_fallback is used to handle errors that may occur when performing the PaymentExecutor service.

Conclusion

The benefits of using the Railway pattern are:

  1. The Controller is thin, easy to read, and maintains and follows the principle single responsibility (the letter S from SOLID).
  2. It is easy to test business logic because it is separate from the controller, and there is no need to emulate POST or GET requests.
  3. PaymentExecutor is easy to expose and not change the code. Otherwise, the principle Open-Close (the letter O from SOLID) would be broken.
  4. The service PaymentExecuter helps to get rid of nested cases.
  5. This approach is convenient to use when there is more than one record and also maintains complex form or business logic.
  6. The red and green paths help to handle errors.
  7. This provides a service with a specification that is easy to read, maintain and understand.

--

--