Grouping callbacks in GenServer - which style do you use?

I group functions with the same name in a Module

defmodule MyMod do
  
  def foo(1)
  def foo({1, 2})

  def bar()

end

But in a GenServer this can get messy when you have several public interfaces as you get a lot of handle_call or handle_cast definitions dealing with the different public interfaces.

What do you do in this case?
You keep all the callbacks grouped together:

defmodule MyMod do
  use GenServer
  ...
  def handle_cast(:foo, _from, %{})
  def handle_cast(:foo, _from, state)
  def handle_cast(:bar, _from, %{})
  def handle_cast(:bar, _from, state)
  ...
end

or group them by case:

defmodule MyMod do
  use GenServer
  ...
  def handle_cast(:foo, _from, %{})
  def handle_cast(:foo, _from, state)
  
  def handle_cast(:bar, _from, %{})
  def handle_cast(:bar, _from, state)
  ...
end

I prefer the latter when the public API is broad

1 Like

I do it ‘by case’ for your example. However I keep one space between functions of the same ‘function’ (or none if they are single line functions), and two spaces between all functions that are not of the same functionality. Just something I’ve been doing since C++ and Pascal 25 years ago. :slight_smile:

1 Like

I’m also influenced by my background in Python, where I use one space between methods in a class and two spaces between functions

1 Like