katafrakt

katafrakt

Providing default implementations - a design problem with protocols

Hi, I’m contemplating writing an admin library, similar to Kaffy and LiveAdmin, but filling a few gaps found while using Kaffy. For that I figure I would leverage protocols instead of giant configs (LiveAdmin) or magic admin modules (Kaffy). But after some initial coding I see a few problems.

What I have right now is this:

defimpl Admin.Resource, for: App.Accounts.User do
  def name(_), do: "User"
  def slug(_), do: "user"

  def form(user) do
    import Admin.FormBuilder

    new(user)
    |> title(if user.id, do: "User #{user.id}", else: "New user")
    |> field(:email)
    |> field(:first_name)
    |> field(:last_name)
    |> build()
  end
end

This is nice, but obviously the number of customizable things grows in time. Not only I want to have customizable form, but also records lists, their fields, custom actions, custom mass actions etc. On the other hand, I don’t want to force user to define all functions when they just may use defaults (for example, no need for custom slug or resource name).

So far I have two ideas and I want to know what you think:

1. Have a macro with default

defimpl Admin.Resource, for: App.Accounts.User do
  # I don't want to customize slug and name

  def form(user) do
    # ...
  end

  use Admin.Resource.DefaultImplementations
end

This has a problem with either having the users remember to put it at the end of the module, so default implementation does not shadow custom implemementations - this is not POLS and what is usually done with use. Also, it generates warnings. Alternatively, there would have to be an option to what default implementations to use, for example:

defimpl Admin.Resource, for: App.Accounts.User do
  use Admin.Resource.DefaultImplementations, except: [:form, :custom_actions]
end

Both are not really great in my opinion, I would especially hate generating many warnings for the user (so using import instead is not great too).

2. Use many small protocols

Alternatively, I could have a protocol for just about anything that is customizable and user would choose what to implement. So we will have Admin.Resource, Admin.ResourceTable.Columns, Admin.ResourceTable.Actions, Admin.ResourceTable.MassActions, Admin.ResourceTable.Query, Admin.ResourceTable.SearchQuery, Admin.Resource.FormCustomActions etc. Each one of these will probably will end up with just one function (call?). Seems sensible to some extent, but I feel that having to implement these many protocols might put people off.

Which solution appeals to you more? Or maybe there’s some alternative I missing? Or maybe using protocols for that wasn’t such a great idea…

Most Liked

al2o3cr

al2o3cr

This sounds like the situation defoverridable is intended for.

zachallaun

zachallaun

Every time I’ve personally started off with a protocol for some generic piece of functionality, I’ve eventually switched to a behaviour. I believe they are both more explicit and more flexible, and lend themselves well to the defoverridable strategy that @al2o3cr mentioned.

defmodule AdminResources.User do
  use Admin.Resource, schema: App.Accounts.User
  # defines default impls for all required callbacks

  # override where needed
  @impl true
  def whatever do
    …
  end
end
BartOtten

BartOtten

That was yesterday, today is a new day!

Which made you valuable for the community already. Take credit :wink:

cognivore

cognivore

You have stumbled upon on the many faces of the expression problem!

One doesn’t need to squint hard that the notion of your architecture to be truly scalable under development (what I mean here, strictly, is to guarantee that at no point in time you have added a new data type such as App.Accounts.User, but forgot to implement some method such as form and, conversely, you have added some method such as form and didn’t match some of the data types such as App.Accounts.User), is the same as the notion of adding a new function and a new type case at the same time.

I think what the colleagues who have answered with defoverridable suggestion imply is something like the idea from the post-scriptum of this post, which is “just being able to scale code base along one function / type case axis is enough for scalable code bases that are also ergonomic”.

That said, defoverridable is not a panacea. It allows you to add more types easily, but based on your question you seem to be more concerned about adding more functions. Furthermore, you venture into the dangerous waters of default implementations which, if unconstrainted, can quickly turn unusable. Ask yourself when have you last seen a useful default implementation that survives class inheritance?!

This is why, I would argue that what you actually need a hierarchy of protocols. One could say, you need traits! Now if you’re able to define your default implementaitons in terms of existing traits, these implementations shall trivially survive subtyping!

If you wonder where can you get hierarchical traits in Elixir, type_class library has got you covered!
What’s more, is that you can be principled about trait methods that you define and add properties for the traits that shall be checked at compile time.

Finally, on ergonomics that you desire.

Consider you have:

defclass A do
  def f(x), do: x
end

defclass B do
  def g(_x, y), do: y
end

defclass C do
  extend A
  extend B
  def h(x, _y), do: x
end

The UX you want is

definst C, for: X do
  def f(x), do: x.c
  def h(x, y), do: {x.c, y}
end

Sadly, the best type_class can do is:

definst B, for: X
definst A, for: X do
  def f(x), do: x.value
end
definst C, for: X do
  def h(x, y), do: {x.value, y}
end

I sketched out an implementation plan for shallow dependency instance definitions here.

In general, I would strongly suggest you having the safest architecture that enforces completeness of function implementations over data types over both developer’s user experience and trying to chase the expression problem. Whatever it means for your particular problem.

tfwright

tfwright

@katafrakt there are a couple of suggestions in this thread you might want to check out: Overridable functions in protocol implementations? - #6 by Ajwah

That said, when I created LiveAdmin I did consider integrating directly with the Ecto schema modules themselves to handle config, but I ultimately decided against it because I wanted something as flexible and light-weight as possible. Personally I preferred to keep that noise out of the application business logic, but other users might prefer to have it in the contexts, or separate per-schema modules, or whatever. It’s certainly true that eventually this can lead to unwieldy configs. However, since the config is just a list, there is nothing to stop the user from leveraging whatever language features they want to specify their config implementations consistently for all the schemas, and furthermore, to pass the result via app level config, rather than per-schema configs in the router. If you wanted to use protocols to contain your config logic, you could do something like this:

config :live_admin, 
  label_with: {Admin.Resource, :label, []}, title_with: {Admin.Resource, :title, []}, ...

and then the router would only need the list of schemas, which is also something you could generate dynamically.

Admittedly, not all config is currently so conducive to that approach and would need additional effort to generate, but I think it should be doable if desired. Maybe that is something I should take a look at formalizing a bit more.

Where Next?

Popular in Questions Top

minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
ycv005
I have followed this StackOverflow post to install the specific version of Erlang. And When I am running mix ecto.setup then getting fol...
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
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
mathew4509
I have a list say x = ["23gh", "56kh", "97mh"] I would like to pass each element to Val in each iteration. Say, in iteration 1 -------...
New
LegitStack
I’m trying to make a websocket server in Phoenix or raw Elixir. I heard about gun, I think I could use cowboy, but since I’m not that sma...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
sergio
I couldn’t find any guides that worked well with Phoenix 1.6.0 and esbuild. I hope this helps people test the waters and eases you into t...
New
sergio_101
I am VERY much an elixir newbie. I have taken one elixir course and one phoenix course on Udemy. During that course, I saw the instructor...
New
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
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