Hal9000
Serialization (Behaviours and protocols)
I’ve been thinking about the topic of behaviours and protocols for several weeks,
basically a cycle of “think, discuss, code, take notes, repeat.”
Someone suggested that serialization would be a good example of something
to implement with a behaviour; someone else said that it was a natural example
for a protocol.
I think it depends on what you mean. Here is my very simple example of a
Serializable behaviour. It couldn’t be rewritten as a protocol, really. But
maybe looking at the problem differently, it could be? After all, simply saying
“serialization” doesn’t fully define the problem.
Still seeking good examples of a custom-defined behaviour and a protocol
to show their similarities and differences.
defmodule Serializable do
@callback load(String.t) :: any
@callback dump(any) :: String.t
end
defmodule MyCollection do
defstruct [:foo, :bar]
def new(x, y) do
%MyCollection{foo: x, bar: y}
end
@behaviour Serializable
def load(str) do
[x, y] = String.split(str, "\n")
MyCollection.new(String.to_integer(x), String.to_integer(y))
end
def dump(item) do
"#{item.foo}\n#{item.bar}"
end
end
x = MyCollection.new(3,5)
dumped = MyCollection.dump(x)
y = MyCollection.load(dumped)
First Post!
imetallica
I would implement as a Protocol just because of one reason: you can extend the serialization to user defined types, for example.
Popular in Discussions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #hex










