Here is my definition of a function:
- A function must have the ability to be called by its name, object, reference, or other handle (this prevents code snippets). The only exception to this is the main method (or equivalent) of a program.
- A function must be able to pass aroundtake data as input by accepting parameters and output data by returning values. If side-effects occur, the function shouldn't exploit them; any parameters should be arguments, and any results should use your language's equivalent of
return
. - Multiple functions can be counted as one function, provided that each helper function meets the 2 previous conditions.
Lastly, as @Downgoat's answer says, if something is obviously not a function, then it shouldn't be treated as such.
A full program is any code that can be compiled, interpreted, or otherwise executed in a non-REPL environment without any modification. Note that some code can be classified as both functions and full programs.
Anything that is not either a function or a full program is a code snippet.
For an example, let's look at Java lambda expressions.
- You can assign a lambda expression to an object, so it passes the handle test.
- It is possible to write a lambda expression that accepts parameters and returns values.
For example:
(int a, double b)->{
return 4;
}
Since a lambda that satisfies #2 exists, any lambda is considered a function, even those that don't accept parameters:
()->{
System.out.println("Lambda is running");
}
- N/A
I made a quick flowchart to categorize various bits of code (sorry for my lack of flowcharting skills):