unaware8150

unaware8150

Hello folks!

So at work, we are seeing some situations where we have to define some “fixed” strings that are used across the codebase in different scenarios:

def start_race(user_1, user_2, "horse"), do: ...

def measurement_unit(%{vehicle: "horse"}), do: "m/s"

def is_animal?(vehicle) when vehicle == "horse", do: ....

def track(vehicle) do
  case vehicle do
    "horse" -> %Track{name: "horse_track"}
    _ -> %Track{name: "highway"}
  end
end

def default_vehicle(_), do: "horse"

if all those function examples are within the same module, then we could extract them to a module attribute as follows:

defmodule Game do
  @horse "horse"
  def start_race(user_1, user_2, @horse), do: ...

  def measurement_unit(%{vehicle: @horse}), do: "m/s"

  def is_animal?(vehicle) when vehicle == @horse, do: ....

  def track(vehicle) do
    case vehicle do
      @horse -> %Track{name: "horse_track"}
      _ -> %Track{name: "highway"}
    end
  end

  def default_vehicle(_), do: "horse"
end

but things get tricky when we have to use `horse` across different modules, because we ended up with lots of `@horse “horse”` definitions and later on if needed to update, it might get tricky.

In order to kind of solve this, the team started to write macros and use them as follows:

defmodule Vehicles do
  defmacro horse, do: "horse"
end

defmodule Game do
  require Vehicles
  def start_race(user_1, user_2, Vehicles.horse()), do: ...

  def measurement_unit(%{vehicle: Vehicles.horse()}), do: "m/s"

  def is_animal?(vehicle) when vehicle == Vehicles.horse(), do: ....
end

defmodule Track do
  defstruct [:name]

  require Vehicles

  def default_vehicle(_), do: Vehicles.horse()
end

which does not sit well with me :smile: but I’m not sure if it’s just me or that pattern is a code smell on its own and there is a better way to handle it. I hope you got the gist of the problem and my pet peeve.

So, anyway, is there a way to handle those “fixed” or constant strings across the codebase in a clean way without losing pattern matching or guard usage ?

Thanks in advance!

Showing Posts 1 to 10

rhcarvalho

rhcarvalho

At a glance it looks like those “strings” really wanted to be atoms?

unaware8150

unaware8150 OP

sometimes, yeah, but not always. Due to the toy example, we could replace them all with atoms but since our code deals with JSON serialization/parsing, sometimes we need to keep the fixed term as a binary string.

Zurga

Zurga

You could create a module that contains all the globals and the inject them as module attributes with use. So:

defmacro __using__(_) do
  quote do
    @horse "horse"
  end
end

And then you can have them as compile time env vars as well. Just replace “horse” with Application.compile_env calls

frerich

frerich

Perhaps you can consider not referencing the same string everywhere. Instead of having N functions each having a clause for horse it might be viable to group all the horse-functions in a single module and then select the module just once. E.g.

defmodule Vehicles.Horse do
  def measurement_unit(), do: "m/s"
  def is_animal?(), do: ...
  def track(), do: %Track{name: "horse_track"}
end

defmodule Game do
  defstruct [:user_1, :user_2, :vehicle]
  def start_race(user_1, user_2, "horse") do
    %Game{user_1: user2, user_2: user_2, vehicle: Vehicle.Horse}
  end
  def measurement_unit(game), do: game.vehicle.measurement_unit()
  def is_animal?(vehicle), do: vehicle.is_animal?()
  def default_vehicle(_), do: Vehicle.Horse
end

I.e. you pass a module around which has all the horse-specific functions.

derek-zhou

derek-zhou

def start_race(user_1, user_2, Vehicles.horse()), do: ...`

It is not just you; I find using macro in function head hard to read.

gregvaughn

gregvaughn

Perhaps this is an XY problem. Instead of focusing on constants, maybe what you want is a Vehicle protocol, with a Horse struct as one implementation.

LostKobrakai

LostKobrakai

Can you elaborate on why you need that?

nikfp

nikfp

Why not use functions? You can execute them into module attributes during compilation and use that value as the match or in guards.

You can define a module that holds the constants as return values of functions:

defmodule MyApp.Constants do

  def horse, do: "horse"

end

Then assign the constants to module attributes in the consumer modules:

defmodule MyApp.Consumer do

  @horse_constant MyApp.Constants.horse()

  def this_needs_to_match(@horse_constant) do
    # whatever code runs when the pattern matches "horse"
  end

  def this_needs_to_match(_fallthrough) do
    # non-matching function
  end

end 

You need to change the string to something else? Change it in the constants module and recompile and you are done.

This looks close to what you are already doing, but doesn’t need a macro to do it. It’s more explicit and reads better to me, and if you have a string that needs to be consistent on what it’s matching but the meaning behind it might need to change for the module, you can name the module attribute anything you want.

windexoriginal

windexoriginal

To elaborate on Greg’s suggestion:

defmodule Vehicle do
   @callback from_json(binary) :: {:ok, struct} | {:error, term}
   @callback track(struct) :: String.t()
   @callback measurement_unit(struct) :: String.t()
   @vehicles [MyApp.Horse, MyApp.Car]
   
   def parse(json) do
     parsed = 
      Enum.reduce_while(@vehicles, json , fn mod, json -> 
        case mod.from_json(json) do
         {:ok, struct} -> {:halt, struct}
         {:error, _} -> {:cont, json}
        end
      end)

     if is_binary(parsed) do
        {:error, "no valid vehicle found in json"}
     else
        {:ok, parsed}
     end
   end

   def track(%{__struct__: module} = s) do 
      try do 
        module.track(s)
      rescue 
       exception in UndefinedFunctionError -> raise "#{module} does not implement vehicle"
      end
   end
end

Now when you add a new vehicle you create a module that implements the Vehicle protocol and add it’s module name to the vehicles attribute in the Vehicle module. If you add more required functions the compiler will warn you if you haven’t implemented them in your modules.

unaware8150

unaware8150 OP

interesting approach! thanks for the suggestion. I might give it a try.

Where Next? Top

Trending in Questions Top

itzmidinesh
Hi all, I’m working on a Phoenix project where I need to make external HTTP requests and I’m trying to choose between Req and HTTPoison....
New
yarrichar
I’m very new to Elixir, so sorry if this is a silly question: I am wondering what happens to the mailbox of a process when the machine i...
New
Hellowman
Hello everyone! I am new to coding with Elixir/Erlang. And i am looking for some utilities for fuzzing testing like AFL++. Does anyone ...
New
pragdave
How do I tell Hologram not to escape HTML when substituting into templates? {Textile.render(@product.long_description)} escapes the HTM...
New
Fl4m3Ph03n1x
Background When trying to execute mix release on a Windows 11 machine for a Phoenix project I get the following error: * assembling mark...
New
rlipscombe
I’d like to create a file with 600 permissions (rw-------), but there’s a race condition if I create it and then change the permissions. ...
New
saleyn
Is there a way to import record definitions in the iex shell for pretty printing (similar to the rr command in the erl shell)? This woul...
New

Other Trending Topics Top

dominicletz
Hey there, I haven’t seen a list of useful Elixir specific skills for the popular AI tools yet so I’m starting one here with my first. ...
New
raa-ziq
Hi everyone :waving_hand: I wanted to share something I’ve been building — NowBlind, a random chat app designed to help people discover ...
New
mudasobwa
I fully migrated to my own harness from Anthropic/Gemini and I think it’s time to share it. Welcome DSH, the DeepSeek Harness, fully writ...
New
OndrejValenta
(I just needed to vent somewhere and LinkedIn is full of hope, or hype, I’m not sure which exactly) AI dream has many faces, but general...
New
kip
Localize is the next generation localisation library for Elixir. Think of it as ex_cldr version 3.0. The first version will be released ...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews