DEV Community

Cover image for How do you order your functions?
Aral Roca
Aral Roca

Posted on

How do you order your functions?

Many linters complain that functionA cannot be declared on bottom of functionB when this is the case:

function first(){
  second()
}

function second(){
  // Whatever
}
Enter fullscreen mode Exit fullscreen mode

This rule will warn when it encounters a reference to an identifier that has not yet been declared.

Rule of Eslint: https://eslint.org/docs/rules/no-use-before-define

So, we will change it to:

function second(){
  // Whatever
}

function first(){
  second()
}
Enter fullscreen mode Exit fullscreen mode

And I've been following this rule in my projects. But I always wonder, if it really matters that much... Since JavaScript seems to handle function declarations well even if they're not in the right order.

And the truth is, we're used to reading from up to down. And for me to do this makes it much more understandable:

function first(){
  second()
  third()
}

function second(){
  fourth()
}

function third(){
  // Whatever
}

function fourth(){
  // Whatever
}
Enter fullscreen mode Exit fullscreen mode

How do you sort the functions? I'd like to hear about this.

Latest comments (34)

Collapse
 
darkwiiplayer profile image
π’ŽWii πŸ³οΈβ€βš§οΈ

I've gotten used to structuring my code files so that helper functions go at the top and library functions then go at the bottom. Since I mostly code Lua, I can call any library function from any other, but with helper functions I don't really mind structuring them so the most low-level ones go on top.

Collapse
 
pentacular profile image
pentacular

Honestly, I think that if you do not have too many functions grouped together, the order does not matter.

The corollary being that if you care about the order of the functions, perhaps you have too many grouped together.

Perhaps the answer is to break them up into smaller, logical groups?

Collapse
 
functional_js profile image
Functional Javascript • Edited

I use arrow funcs exclusively, thus ordering by definition before invocation is runtime enforced. ;-)

Most of my modules have one func.
My utility modules have many funcs, but order doesn't matter since there is no dependencies between any of them; if anything they're arranged by general similarities.

But that's also trivial because I get to a func by hitting F12, or alt-F12 to get preview-popup. If I'm in the utility module, I use ctrl/cmd-shift-period to pull up the list of funcs. You can also type in that list to highlight the func you want, then hit enter to go to it.

So where a func is inside of a code file is the least of my concerns.
The more common concern is pondering, "Do want to pull this func out into its own module?"

Collapse
 
fhammerschmidt profile image
Florian Hammerschmidt

Use a language which does not even allow to use a value or function before declaration (i.e. the compiler yields an error) and structure the low-level internals into nested modules.

For instance in ReasonML:

module Something = {
  let readInput = () => ();
  let writeOutput = () => ();
};

let doSomething = () => {
  Something.readInput();
  Something.writeOutput();
};

This makes it also very easy to factor out the module into a separate file later, when the file at hand becomes too big, because a file in ReasonML is also just a module.

Collapse
 
aguynamedjonas profile image
Jonas Peeck

Clean Code suggests an awesome analogy imho of ordering functions like they are an article in a newspaper:

Most important statement up top, then comes the subheadline, then the first paragraph that tells you everything you need to know and then the gritty details.

So essentially order by abstraction layer as others suggested, enhanced by thinking about what the most important LOC in that file are that somebody opening this file needs to read first.

Collapse
 
msamgan profile image
Mohammed Samgan Khan

according to the PRS standards function which are same should be close to each other. so this is a better paractice.

Collapse
 
perpetual_education profile image
perpetual . education

Order of importance. Just like CSS. But - not saying that's the 'best' way.

Collapse
 
elmuerte profile image
Michiel Hendriks

The deeper is goes, the lower it gets.

Collapse
 
adiluddin profile image
Adil • Edited

There's something called as Stepdown rule when it comes to writing functions, here's an example:
dzone.com/articles/the-stepdown-rule
This is also suggested by uncle Bob in the clean code handbook.

Collapse
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

But, does it even possible for some languages that have functions are first class citizen, such as Python?

I mean, class methods?, no problem. JavaScript with function keyword?, no problem. But what about the others?

Collapse
 
gwutama profile image
Galuh Utama

Python, yes. C/C++, yes (you declare the functions first in header). Bash, yes.

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

Python?

This does not work. (If you put if __name__ == '__main__': at the bottom, it will work, though.)

But this does work in JavaScript. Don't know whether I should do it, though.

makeBreakfast()

def makeBreakfast():
  addEggs()
  cook()
  serve()


def addEggs():
  print("""
  fridge
    .getEggs()
    .forEach(egg -> fryingPan.add(egg.open());
  """)

def cook():
  print("""
  fryingPan.mixContents();
    fryingPan.add(salt.getABit());
    fryingPan.mixContents();
  """)

def serve():
  print("""
  wife.give(fryingPan.getContents(20, PERCENT));
    self.give(fryingPan.getContents(80, PERCENT)); // huehuehue
  """)
Thread Thread
 
gwutama profile image
Galuh Utama

Well that's true.

if __name__

must be written on the bottom. However here's I always do it in python:

#!/usr/bin/env python

def main():
    foo()

def foo():
    print("foo")
    hello()

def hello():
    print("Hello, world!")

if __name__ == "__main__":
    main()

Ordering functions from the highest abstraction to lower works this way.

Thread Thread
 
patarapolw profile image
Pacharapol Withayasakpunt • Edited

It is always nice to see a runnable code, and if possible, IRL open source projects. Thanks.

And I also want to say, this also works regardless of being outer scoped.

#!/usr/bin/env python

def foo():
    print("foo")
    hello()

def hello():
    print("Hello, world!")

if __name__ == "__main__":
    foo()
  • I think main() has no real meaning. But if __name__ == "__main__": as well as anything in __main__.py do. main() may help in unittesting, though.
  • About #!/usr/bin/env python, at least for me, it is rare to make Python only one-file. Often, there are modules, probably with top-level app.py. So, I only put shebang once.
Thread Thread
 
gwutama profile image
Galuh Utama • Edited

Yes, main() is just common to see. By no means it has to be called main().

Here's an example from docker-compose:

The entry point is here

It doesn't even use the usual if __name__ ...

from compose.cli.main import main

main()

which calls this module

Check out the main() function there. It's defined at the top of the file and it calls lower level functions there.

Regarding the hash bang, yes I just do it out of habit. I often use python to replace bash to write small command line tools, which in my case, often in single files.

Collapse
 
simondell profile image
Simon Dell

I agree with your suggestion. "top to bottom" is much easier to read.

I rarely write code this way, however. I tend to group my functions around the domain they operate on, and then alphabetically, except where that causes linters to complain. I think you've managed to show me I need to rework my linter rules ;-)

Generally, however, I think lists of any programming token (functions, imports, parameters, members of an object/dictionary) are best entered in alphabetical order, when you work in a team. It's a very easy rule to remember and follow, and prevents wasted time during code review. It also supports how git works (line by line), so you have fewer conflicts when merging branches.