Best way to keep Atoms, Strings, and Integers consistent while passing messages between processes?

My code always gets jumbled up with atoms and strings, or strings and integers, which causes functions like MapSet.member? to return false, even if I am expecting it to be true. Or I send a %{event: "hello"} to a process, but it actually expects %{event: hello}.

To solve this, I create functions like maybe_atom_to_string or maybe_int_to_string and put them wherever variables are being sent to another process to keep things consistent.

Is this a code smell? Is there a better way to do this? Do I just need to be more careful when sending messages around processes?

Yes. You should always be fully aware of which datatypes you’re juggling. At the edges of your system you should have code, which normalizes data once into the datatypes you expect, so moving forward they’re correct.

6 Likes

And you can use event structs, %Thing.Events.SomeThing{typed: "variable"} and/or typespecs internally to help.

If you’re gonna use structs the typed_struct lib is worth a look :eye: