Public and private functions correct ordering in module

Hello all,

I tried to find what is the correct ordering of public and private functions in a module but I could not find an official answer. Should private functions be grouped together with the public functions that use them or should they be kept alphabetically at the end of the module?

Thanks a lot for any help,

FWIW, the language implementation prefers defps close to the caller:


Thanks for your answer.

I tried to find the solution in this doc but I couldn’t: Elixir Style Guide

Maybe there isn’t an official way to do this?

I speculate that might be because it’s hard to make an easily documented rule about it.

In many cases, we’re encouraged to write small declarative functions in lieu of in-function conditional/branching logic. This means you may well end up with a bunch of defp functions which serve the conditional needs of a single function and possibly no others. In such a case, keeping them close to where they’re called is very good and not difficult.

But other times you might have defp functions which are useful in a number of calling functions. What’s the rule for those? Keep close to the first caller? The last caller? Arguably these utility functions can be justified at the end of the module or even the beginning. I’ll tend to follow the rule that shared private functions like that go after the last caller and the last caller’s specific private functions; I like publicly callable functions to be more front and center so they go first… except for that first case of closely coupled definitions.

Anyway, I guess my point is that once you get away from that first case there are varying arguments for placement that can be circumstantial or simply preference based in a way that’s difficult to create an acceptable, pubic style-guide for.

1 Like