Onor.io

Onor.io

Three Ways To Share Values Between Modules

A new REPL on Replit to help demonstrate three techniques to safely share values between modules. DRY up your code in a safe way!

defmodule MyMath do
@moduledoc """
This repl documents three ways to share values between modules.  

The question may occur to the reader--why would I want to share values between modules?  It's a valid question.  It is often the case that we need to share some common piece of logic among different contexts.  For example if we use a regular expression (regex) to parse, for example, an address, we want to insure we use the same regex every place we need to parse an address.  We can certainly copy/paste the regex but that leads to a lot more work for later developers who if they find they need to modify the regex must insure they find all the uses of the regex and modify all of them.  This becomes an even larger issue when you have teams of developers, potentially distributed across geography.  Communication is already a problem in that case and it's far more likely that someone will miss something. 

The following repl is structured as one file with two modules to make it easy to run and observe the behavior.  The Main module gives examples of how to use the shared values across modules. 

You can try the following in the console to assure yourself that this all works as expected:

## Examples

iex>  radius = 3.0
3.0
iex>  Main.circle_area(radius) == Main.circle_area_alternate(radius)
true
iex>  Main.circle_area_macro_approach(radius) == Main.circle_area(radius)
true
"""

   #First symbolic constant technique: module attribute
   Module.register_attribute(__MODULE__, :pi, persist: true)
   @pi 3.141592653

   #Second symbolic constant technique: function to return constant value
   def pi, do: 3.141592653
   # this could also be: 
   # def pi, do: @pi

   #Third symbolic constant technique (many thanks to Paul Schoenfelder for this): macro 
   defmacro __using__(_) do
    quote do
       @pi 3.141592653
    end
  end
end

defmodule Main do
   defp get_pi do # module attribute approach
      [pi] = MyMath.__info__(:attributes)[:pi]
      pi
   end

   def circle_area(radius) when is_float(radius) do
      MyMath.pi() * radius * radius #constant function approach
   end

   # or
   def circle_area_alternate(radius) when is_float(radius) do
      get_pi() * radius * radius
   end

   # or
   use MyMath

   def circle_area_macro_approach(radius) when is_float(radius) do
    @pi * radius * radius
   end

end

Try it out on Replit here!

Most Liked

Onor.io

Onor.io

Thanks for moving this to the right place. I tried posting under Learning Resources but I couldn’t.

Yeah I figured people would just click the Run button and then try the examples but I can see how that may be not as obvious as I would have hoped.

Where Next?

Popular in Guides/Tuts Top

WolfDan
So my main OS is Windows, I do must of my work with it, Elixir and vscode elixirls works just fine when you’re working only with elixir, ...
New
jswny
Hello everyone, I recently redesigned my entire deployment process for Phoenix apps based on Docker. I really like the strategy that I ca...
New
sergio
https://sergiotapia.me/generate-images-with-name-initials-using-elixir-and-imagemagick-374eca4d14ff Hope this saves you guys some time!...
New
niku
I write an article Parameterized testing with ExUnit.The key concept is using ExUnit.Case.register_test/4 such as ExUnit.start() defmod...
New
Eiji
Hey, today I give amnesia library a try and found a few problems. I would like describe how to setup it properly and solve problems which...
New
TwistingTwists
This is a thread to note down things/best practices encountered in LiveBeats App as I explore the source code. https://github.com/fly-...
New
jtormey
Hello! Having written a lot of LiveView code, I’ve made some VS Code snippets to speed up writing callbacks for LiveViews and LiveCompon...
New
niku
I have published an elixir project with using Travis CI. I would like to share some tips & thoughts that I was getting through this ...
New
smpallen99
Some advice for Elixir programmers. I was reviewing someone’s Elixir Code yesterday and found a deadlock condition bug in a GenServer im...
New
nelsonic
When we were figuring out how to use Phoenix LiveView we got stuck a few times. So in order to save other people time, we created a comp...
New

Other popular topics Top

Nvim
Anybody knows a comprehensive comparison of Django and Phoenix, thanks for the help. Where are they similar? Where do they differ the m...
New
Patoshizzle
After calling mix ecto.create I get this error: 17:00:32.162 [error] GenServer #PID<0.412.0> terminating ** (Postgrex.Error) FATAL...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? Ecto.Repo — Ecto v3.14.0 has exampl...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
nsuchy
Hi. I’ve noticed that Windows Powershell has it’s own IEX command and you cannot access Elixir’s IEX due to the conflict. This isn’t a cr...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New

We're in Beta

About us Mission Statement