Why SOLID may be useful for you in Elixir
Tags: erlang, elixir, solid, patterns
Published: 2021-04-26 07:51:59

---
title: Why SOLID may be useful for you in Elixir
published: true
description: 
tags: Erlang, Elixir, SOLID, Patterns
//cover_image: https://direct_url_to_image.jpg
---

## Intro

Software development is difficult. One of the ways to overcome difficulties of building software is to use so-called architectural patterns, for example well known [SOLID](https://en.wikipedia.org/wiki/SOLID) principles.

But trying to apply these principles in Elixir we often hesitate:

  * Could these principles be even applicable? Don't they refer to classical OOP languages, while Elixir is a functional language?
  * Are these principles useful at all? Does this stuff even refer to programming practice and not only to "clever" books with fictional class hierarchies of rectangles and squares? This is even more disturbing when our everyday work consists mostly of putting code into predefined places provided by "frameworks": views, controllers, models, etc.

This article is a small attempt to illustrate positive answers to these questions with real issues of a real OSS Elixir library ([SMPPEX](https://github.com/funbox/smppex)).

## SMPPEX

[SMPPEX](https://github.com/funbox/smppex) is an Elixir library for interacting via [SMPP protocol](https://en.wikipedia.org/wiki/Short_Message_Peer-to-Peer). It is popular for interfaces of mobile operators.

The structure of this protocol is not very important, it's enough to say that it is an asynchronous binary protocol over TCP.

SMPPEX is based on [ranch](https://github.com/ninenines/ranch) and handles TCP connections in the following way:
![SMPPEX Scheme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5p4zhymxwvkvmy5kulef.png)

### Behaviors

We need to say a few words about _behaviors_. Behaviors is an Erlang way for specifying interfaces. Each Erlang (and Elixir) module can define so-called `callbacks`:

```elixir
defmodule Foo do
  @callback bar(a :: pos_integer(), b :: String.t()) :: String.t()
end
```

Then, any module can implement this behavior:

```elixir
defmodule FooImpl do
  @behavior Foo

  @impl true
  def bar(a, b) do
    String.duplicate(b, a)
  end
end
```

After that this module can be safely used whenever `Foo` beahaviour is required.

```elixir
def do_smth(foo_impl_module) do
  ...
  s = foo_impl_module.bar(5, "abc")
  ...
end

...

do_smth(FooImpl)
```

### Behaviors in SMPPEX

There are two main modules for handling sessions (see picture).

  * `SMPPEX.TransportSession`. It works directly with TCP socket, transforms binaries from socket to protocol structs (PDUs) and vice versa, sends PDUs and handles TCP errors. It also defines `SMPPEX.TransportSession` behavior: callbacks for more intellectual PDU handling.
  * `SMPPEX.Session`. It implements `SMPPEX.TransportSession` behavior. Responsibility of `SMPPEX.Session` is to make pings, handle timeouts, correlate request PDUs with response PDUs and so on. `SMPPEX.Session` also defines its own behavior: callbacks for placing user defined logic.

So, when implementing an SMPP "server" or "client" (called MC and ESME respectively), one should implement `SMPPEX.Session` behavior.

## Answer to the first question

We see that Elixir allows to define interfaces and to provide polymorphic access to programming entities. That's a major part of OOP (if not the whole OOP according to some definitions). We also have a real example of using this mechanisms in practice.

This allows us to conclude that Elixir code *can be a subject* of analysis through SOLID principles.

But is this practically useful?

## History of a (very) small Pull request

SMPPEX is a library for quite a specific domain, that's why it is not super popular, but still has a worldwide user base. From time to time users submit their reports and improvement suggestions.

Once I received a [PR](https://github.com/funbox/smppex/pull/69/files) with a reasonable suggestion: add [telemetry](https://github.com/beam-telemetry/telemetry) integration.

![PR](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fd2tjfc1eek069vvsw2f.png)

Telemetry is an Erlang library for tracing arbitrary system events and for handling them independently.

This functionality seemed to be quite useful, but the proposed solution made me think a bit. After some consideration I realized that I wanted to see another solution to problem.

### S and O from SOLID

What made me think so? I think that was subconscious expectation of possible difficulties with supporting this code, but it were the SOLID principles which helped me to come to rational explanation of the feelings.

#### S

S in SOLID stands for _The Single-responsibility principle_:

> There should never be more than one reason for a class to change.

Obviously we have no _class_, but have a module. It is often somewhat difficult to understand what does "reason" mean. That's why I often use another formula of this principle:

> There should never be more than one party interested in modifying a unit of code.

Obviously, we were going to violate this principle: there were two apparent parties which wanted to share a single module (and even function): me as a supporter of the whole library and the team which needed this functionality and made the PR.

#### O

O in SOLID stands for _The Open-closed principle_:

> Software entities ... should be open for extension, but closed for modification.

In other words, if we want to add new functionality, our architecture should allow us not to put it into existing classes and functions, but to compose new entities and utilize them.

Obviously, we were going to violate this principle too: completely new and unrelated functionality was going to be added to an existing function.

### Practical issues

Probably we shouldn't be strongly concerned if some theoretical constructions are wrecked. That's why we need to demonstrate real-life issues which arise when these principles are violated.

#### Code ownership

Violating S-principle and mixing concerns in a single function or module lead to inconveniences for all parties interested in the code.

Obviously, as a maintainer of the library, I want the core to be well documented, well tested, and so on. After receiving the new code it would have been harder for me to test code, to modify it and even understand.

On the other hand, the team which needs this code would like to modify it as fast as is needed for their business and not to wait for my spare time.

#### Tiers of code

Even if this functionality is worth being included (and it actually is), we often want to have different "tiers" of support for our code. Our "core" code should be well tested, well documented and have wider compatibility (and in case of SMPPEX it really is: see [documentation](https://github.com/funbox/smppex) and [compatibility matrix](https://github.com/funbox/smppex/blob/master/.github/workflows/elixir.yml#L19)).

At the same time supplementary code may not be so well documented or may be compatible only with newer versions of tools.

#### Dependencies

As can be seen, the proposed PR [brings a new dependency](https://github.com/funbox/smppex/pull/69/files#diff-dfa6f4ed74c90e5d4fda283d547d366586e690387289bcfd473e3fa5f9ace308R44): `telemetry`. Although it is a useful library, additional dependencies often bring problems and conflicts. It an issue even in such a small library as SMPPEX (see, for example, this [issue](https://github.com/funbox/smppex/issues/83)), that's why it tries to depend only on Ranch.

We want to allow users of the library to resolve conflicts in minor functionality (even, for example, forking or reimplementing it) and still use the stable core.

Additionally, `telemetry` is still at `0.x` versions and one may just not want to depend on `0.x` libraries.

### Solution

So my proposed solution was:

> Hello!
>
> Thanks for the proposal.
>
> But as far as I can see, the proposed solution violates the Open-closed principle. We shouldn't add orthogonal functionality to existing modules and functions.
>
> One may do the following not to violate the Open-closed principle. Since `SMPPEX.Session` implements `SMPPEX.TransportSession` behavior, it is possible to create a "proxy" session which
>
> * Implements `SMPPEX.TransportSession`.
> * Contains only telemetry-sending logic.
> * Passes all the handling to the encapsulated `SMPPEX.Session`.
>
> Moreover, this can be probably implemented without changing original modules at all.

![SMPPEX New Scheme](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q2ds0fwcjz3gafvxprc6.png)

`SMPPEX.TelemetrySession` is the mentioned "proxy" `TransportSession`.

This complies with the mentioned SOLID principles.

  * We do not violate S adding new functionality into a new module.
  * We do not violate O because we extend functionality composing unchanged old entities and new ones.

### Profits

A bit later I was glad to find out that the team tried and [successfully implemented](https://github.com/caktus/voomex/pull/43/files#diff-3b74415873a3dd8769241d910c1fa0e3e40c310f30557a46e74e06331474d5d5) this approach!

Following SOLID principles allowed them to avoid many inconveniences: not to wait for the maintainer (me), not to fork the project just to add some lines of code. I didn't even know that the work was in progress!


## `smppex_telemetry`

Later I implemented the solution as "batteries": [savonarola/smppex_telemetry](https://github.com/savonarola/smppex_telemetry).

You can see that this is a standalone library, which has a smaller compatibility matrix and it is enough for it to have just a README. It also has a dependency which the core library doesn't have.

## Conclusion

I think this is a small but good example of how SOLID helps to build software and to make communications simpler. So we can frankly answer to the second question: yes, SOLID principle can be applied in practice and can help in better software building.