DRY: what's the Erlang way of dealing with this scenario?

Hi all,

I have many modules that looks the same:

-module(m_one).
-behaviour(some_behaviour).
-export([some_f/2]).

some_f(X, Y) ->
    ...
    M = helpers:m_of(?MODULE)
    Z = erlang:apply(M, some_function, [])
    ...
-module(m_two).
-behaviour(some_behaviour).
-export([some_f/2]).

some_f(X, Y) ->
    ...
    M = helpers:m_of(?MODULE)
    Z = erlang:apply(M, some_function, [])
    ...

The only thing that changes in these modules is the M variable.

Is there a way to avoid repeating some_f in every single module?

Thank you.
Cheers!

1 Like

If you want some_f/2 to be exported from a module you must declare it there, and there is no way to avoid that. However, you can reduce repetition by moving the meaty bits to a helper module:

-module(helper).
-export([help/3]).

help(M0, X, Y) ->
    M = helpers:m_of(M0),
    Z = erlang:apply(M, some_function, []),
    %% ... et cetera
-module(m_one).
-behaviour(some_behaviour).
-export([some_f/2]).

some_f(X, Y) -> helper:help(?MODULE, X, Y).
-module(m_two).
-behaviour(some_behaviour).
-export([some_f/2]).

some_f(X, Y) -> helper:help(?MODULE, X, Y).
3 Likes