//STYLE: Separate and comment your functions

Good programming is about good organization

Divide and conquer!

It is best to divide your code into functions that have separate tasks.

There are good reasons for this. Most importantly, modularizing your code helps you think clearly about how your code works. Breaking your code into separate functions for main, initialization, input, processing, and output helps you stay mentally disciplined and helps you to avoid spagetti code.

There are other reasons as well. For example, most languages have very similar structures for initialization and processsing, but very different structures for input and output. Modularized code helps you to easily port your language to other languages.

It also makes it very easy to make improvements later on. Want to keep your processing intact, but use a drag and drop interface for input instead of typing? Then simply change the input functions and your program will run like normal. Want to add a graph to illustrate a mathematical calculation? Just add it to the output functions.

Five kinds of functions

Remember that there are five general kinds of functions:

Main

This is the controlling function that calls the others.

We comment it like this:

//MAIN: this triggers all the other functions
function mainProcedure () 
    initVariables();
    getInput();
    processInput();
    outputResults();
}

Initialization

This sets up the initial values for your variables.

Sometimes it occurs at the beginning of the program before the main function is called.

We comment it like this:

//INIT: this sets up the initial values of variables
function initVariables () {

}

Input

Input functions are ones that read input from the user.

There are many kinds of input: typing, keyboard control, mouse movement, clicking, uploading a file, taking a picture, reading a website, and much more.

We comment input functions like this:

//INPUT: this reads the input from the user
function getInput () {

}

Process

Process functions are where the bulk of the calculations are done. If decisions are made and things figured out, it happens here.

We comment process functions like this:

//PROCESS: this processes the input and returns a result
function processInput () {

}

Output

Output functions that the results of the processing and show it to the user.

Output can be updating a list, animating something, playing music, turning the temperature down, or many other things.

We comment output functions like this:

//OUTPUT: this outputs the result
function outputResults () {

}