Should functions go before or after setup() and draw()?

I know that it doesn’t make any difference as to how the program is run, but is it good practice to put functions you have declared before or after setup() and draw(), or is it just personal preference?

  • Does it make a difference if you are using other processing functions like keyPressed()? (and where should they go)

  • Does it depend on where the function is called from?

Up until now I have been putting all my functions after setup() and draw() as I feel that it can make it easier to read setup() and draw() without having to scroll past loads of functions, is this approach right?
Even if it is just opinion, I would like to hear what other people do, and why.

Thank you in advance,

The Wizard Bear

This is going to come down to personal preference. Do whichever one makes the most sense to you.

If you’re working on a team, then you should come up with a standard that everybody follows. But it sounds like you’re just working alone, so stick with whatever you prefer.

You could find somebody else’s convention and adopt that. Googling something like “java conventions private function placement” returns a ton of results, including:

Long story short, grouping the Processing functions like setup(), draw(), and mousePressed() first is fine. Another approach would be to group related functions together, for example if you called a function from inside setup(), it might make sense to put that right beneath setup() before draw().

But in the end it’s completely up to you.

There are other conventions that are much more important to follow, such as giving your functions and variables good names and using proper capitalization.

3 Likes

There is no “right” approach but I tend to do this and most contributors to the forum seem do the same. I also tend to group common functions together e.g. event handling functions.

For larger programs you might consider having multiple tabs with common functionality in each, just name the tabs to describe the functionality in the tab.

2 Likes

Also white space (tabs and blank lines) to highlight the program structure

2 Likes

Thanks @Kevin for the advice.
I shall definitely check out some of those links and look into it further.

Thank you @quark for the reply and helping me out!

Both @Kevin and @quark both gave awesome responses, and I’d like to just add, it does have lots to do with preference and background. In C++ there is “forward declaration” meaning you have to put your functions first, just to keep the compiler happy. In most languages though, I would be bold enough to say that where you put it doesn’t necessarily matter :grin:

EnhancedLoop7

1 Like

Thanks @EnhancedLoop7! :grin:

1 Like