BlueStyle icon indicating copy to clipboard operation
BlueStyle copied to clipboard

Function declaration ordering

Open rofinn opened this issue 2 years ago • 4 comments

Does anyone else wish we had a convention on ordering of functions in a file? I typically find putting private (more specific) functions further down in a file is more readable, but I don’t think that’s consistent. I also think some folks prefer the opposite to make copy-pasting into a REPL more intuitive? I suppose you could make the claim that they should just live in a different utilities file, but if they’re only used in that one file it’s kinda nice to keep them together...

rofinn avatar Feb 24 '22 20:02 rofinn

My preference is usually a topological sort, so functions below depend on functions above. I find this reduces the amount of jumping around the file I do while reading code as by the time I'm reading a function I will have encountered all the functions it calls.

iamed2 avatar Feb 24 '22 20:02 iamed2

This is something which I've gone back and for on for quite some time, and still don't have an answer that I really like sadly.

The few things that I've tried so far,

  • Internal functions at the top of the file, prefaced with an _ then your exported functions at the bottom. When I read through the file, I can make quick notes of what these functions are doing, then get to the meat of the file at the bottom. Also the order of these functions is then laid out such that no function which depends on another is out of order
  • If there are a lot of internal functions, say 7+, I pull them into a utility file and then reference them that way

mattBrzezinski avatar Feb 24 '22 20:02 mattBrzezinski

I've personally no strong opinions about the ordering, only that consistency within a file is good (don't have "helpers" both above and below the function that uses them, if you can help it, as that leads to the most jumping about).

I think i tend to put the "main" function top, and helpers after.

But perhaps a very small reason to favour the other way is that @generated functions require it:

Generated functions are only permitted to call functions that were defined before the definition of the generated function.

nickrobinson251 avatar Feb 25 '22 10:02 nickrobinson251

@nickrobinson251 that may very well be how I picked up this habit, after working on AxisArrays

iamed2 avatar Feb 25 '22 21:02 iamed2