Function generation / dynamic dispatch

That says they are either on the wrong file or not put in early in the compilation process.

Honestly I’m thinking this is just a bit odd of a design overall regardless, I would probably just hardcode those all in as it’s not like they are going to be changing often anyway and adding new ones is easy. ^.^;

If you really want to go the more complex route (which be sure that you do), I’d really say take a look at my afore-mentioned protocol_ex, your solution might look similar to (typed in-post so likely has syntax errors):

# Define the main module:
import ProtocolEx
defprotocolEx Blah do
  def parse(header, data) # Since no fallback body then this must be handled by the implementations

  def parse(<<header::integer-little-8, data::bytes), do: parse(header, data)
end

Then just write the implementations like:

import ProtocolEx
defimplEx Login, 1, for: Packet do
  def parse(_, data) do
    # whatever you need here...
  end
  # You could add more `parse/2` callbacks here that handle other numbers as well if you want,
  # or make other implementations like below
end

Then maybe another one somewhere else:

import ProtocolEx
defimplEx Chat, 2, for: Packet do
  def parse(_, data) do
    # whatever you need here...
  end
end

Etc…

And of course you can add a run function and all sorts as well too. Whatever. (If you need new features in protocol_ex, just ask). It has a lot of other abilities and optimizations and such you can do as well, but as-is it already does what you posted that you want.

Don’t forget to add the compile for protocol_ex to the mix.exs file as per the documentation too (or you can always handle it manually too if you want).

(EDIT: Updated examples to be actual code rather than just placeholder code)

4 Likes