Code style: Main functions on top, small functions on bottom or vice-versa?

When programming a module in Elixir, I like to start my module with one or two ‘main’ functions that show the main flow of data that will go on in here, and then write out the ‘small’ functions that are used internally in there.

I find this to be very readable, and giving future readers the opportunity to first see the problem from afar, and then zoom in to the part where you think something might need to be changed or updated.

Now I’ve seen multiple people writing modules in the opposite fashion, with the smallest (often private) functions on top, and the main functions at the bottom. I personally find it less nice to read, but are there any advantages of this approach?

1 Like

I do prefer to have public stuff at the very top of my source files, sorted by importance, after that all the private stuff in random order¹. Organizing the module this way, makes public stuff much more discoverable.

Nevertheless, especially when getting back from a C, C++, Idris, or Agda marathon, I often code in the opposite direction, because all of these languages need to have at least declare before use.

1: Whenever I realize there is a new private necessary I hit PgDn a couple of times, and when my cursor is in the section of private functions, I start to code/hack where I am.

2 Likes

This is indeed a nice question. Reading through Programming Elixir, I’ve got an impression that each public function should have its private helper functions grouped directly under it. This is certainly made easy by such a compact privacy notation of def and defp.

Still, I didn’t find any info about this neither in the book nor in other articles (such as the style guide). Maybe it’s a delicate matter and no one wants to enforce one way.

I’d also suggest taking a look at source code of serious repos like Elixir, Phoenix or Ecto. I find Elixir sources nicely written and highly readable.

1 Like