Formatting question!

Hey guys! So, not that this is ridiculously important to programming, but when looking at someone's code, which do you prefer, the global variables all declared before setup, or declared as it goes before each function? I'd do a poll for this but I don't know if the Processing forum allows you to do something like that. Thanks! :)

Tagged:

Comments

  • edited November 13

    By convention, the order of a Processing sketch is usually:

    A static sketch:

    1. any library import statements
    2. any global variables
    3. everything else (code, no setup, draw, functions or classes)

    An interactive sketch:

    1. any library import statements
    2. any global variables
    3. setup() [1]
      • size() [2]
    4. draw() [3]
    5. everything else (functions and classes)

    • [1] Optionally, you may include settings() before setup() if you need it -- although this is rare.
    • [2] Recommended as first line, as a surprising number of things presume that the width and height have already been set.
    • [3] New programmers often fail to put background() at or near the top of draw -- this is a common first step for the majority of animated programs.

    This sequence is true of almost every example in the reference, tutorials, examples, library examples, and most sketches on this forum.

    If you have a method that works for you and is consistent, you can use it -- just be aware that others may be very confused reading your code if you hide global variables between functions.

  • can I quote you with that?

  • Sure! I've edited the answer to make it a bit more complete. Although you could also quote from getting started or the anatomy tutorial.

    I don't think the official materials every say outright anywhere that "you have to put setup first" because ... you don't have to. But, by convention, almost everything does.

  • https://Processing.org/tutorials/overview/

    The size() function must always be the first line inside setup().

    It's advisable to place the size() function as the 1st line inside setup().

    ... you must select Import Library, then PDF from the Sketch menu.

    ... you need to select Import Library, then PDF from the Sketch menu.

  • Good points -- added some details on settings / setup / size.

Sign In or Register to comment.