Terminology – Specific Meanings of Functions, Methods, Procedures, and Subroutines

terminology

I'm wondering what are the specific differences in the terminology we use for grouping related parts of code. I've sometimes seen the terms used interchangeably: many OO languages even use the keyword "function" to define a method. (Why?)

If you wanted to be precise, what are the specific meanings of each? Or is it just whatever each language chooses to call it?

Best Answer

  • subprogram, subroutine
    "subroutine" probably comes from assembly language. Some processors include instructions to support subroutines as a way of organizing code and reusing common sections of code. For example, the 6502 processor had JSR (jump to subroutine) and RTS (return from subroutine) instructions. I remember it also being used a lot in structured programming, in which a program is a hierarchy of units of code which were sometimes called subroutines or subprograms. IMO, these are the most generic terms for some unit of code to which control is temporarily transferred for the purpose of completing a given task.

  • function, procedure
    These are often used interchangeably, but in some languages there's a distinction. In Pascal, a function is a subprogram that returns a value, while a procedure is a subprogram that doesn't. In C and related languages, every subprogram has a return type (even if it's void), so there's no distinction.

  • method, member function
    These are two names for the same thing -- essentially a function that's associated with a given class or object.

  • operator
    Every language has a set of built-in operators. In some languages, such as C++, operators are functions that can be overridden (i.e. replaced) and/or overloaded (i.e. defined for new types).

  • anonymous function
    This refers to a function without a name. Anonymous functions are essentially blocks of code that can be assigned to variables or passed as parameters for subsequent use, for example as a completion routine.

  • closure, lambda expression, block
    A closure is a chunk of code that's bound to a set of variables. I think of closures as anonymous functions plus context.