An exercise in semantics - Method vs Function
Tags: programming, theory, semantics
Published: 2024-06-01 13:21:30

In the programming terminology, we often encounter the terms *method* and *function*. Let's engage in an exercise in semantics, broadening our understanding to consider the contextual nuances that shape both terms.

In many programming languages, such as JavaScript or Python, modules or namespaces provide a structural framework for organising code and enforcing encapsulation. Within these constructs, functions can be grouped together, forming cohesive units of functionality within a specific context. It is within this context that we propose a reevaluation of terminology.
## TL;DR
In OOP, a *method* is a function that is associated with an object.

In a more general form: In programming, a *method* is a function that is related to a context and whose visibility/accessibility is restricted by that context, where *context*, *relation to the context* and *visibility/accessibility restriction* all depend on the specific programming language considered.

## Introduction
The terms *method* and *function* are often used interchangeably, but there are key differences between them, especially in object-oriented programming (OOP). The following sections provide a detailed comparison.

## Function
- **Definition**: A function is a block of code designed to perform a specific task. It is defined independently and can be called with parameters to execute its task.
- **Context**: Functions are not inherently associated with any object. They can be standalone or part of a module.
- **Usage**: Functions are used to encapsulate reusable code and can be called from anywhere in the program if they are in scope.
- **Syntax Example** (in Python):
  ```python
  def add(param1, param2):
      # function body
      return param1 + param2
  ```

## Method
- **Definition**: A method is a function that is associated with an object. In OOP, methods define the behaviours of an object and can operate on data contained within the object (its attributes).
- **Context**: Methods are defined within a class and must be called on an instance of that class (or the class itself for class methods).
- **Usage**: Methods are used to manipulate the data of an object and to perform operations related to that object. They can access and modify the object’s state.
- **Syntax Example** (in Python):
  ```python
  class MyClass:
      def add(self, param1, param2):
          # method body
          return param1 + param2

  # Creating an instance of MyClass
  obj = MyClass()
  # Calling the add method on the object
  result = obj.add(1, 2)
  ```

## Key Differences
1. **Association**:
   - **Function**: Independent, not tied to any object.
   - **Method**: Bound to an object (instance method) or a class (class method/static method).

2. **Self Parameter (Python Specific)**:
   - **Function**: No implicit parameter.
   - **Method**: The first parameter is typically `self` for instance methods, which refers to the instance of the class.

3. **Calling**:
   - **Function**: Called directly by its name (if in scope) or via module reference.
   - **Method**: Called on an instance or class.

4. **Scope**:
   - **Function**: Can be globally scoped or limited to a specific module.
   - **Method**: Scoped within the class definition and often interacts with the instance's attributes and other methods.
## The case of static methods in Java

Given the definition of a method provided supra, one may wonder why static methods in Java should be called *method* instead of *function*: static methods are indeed not linked to an object.

In Java, static methods are linked to a class rather than an instance of the class, but they are still considered methods for several reasons rooted in object-oriented programming principles and terminology:

### 1. **Context and Namespace**
- **Class Context**: Static methods belong to the class's namespace and are defined within the class body. Even though they do not operate on an instance of the class, their definition within the class ties them to the class's scope.
- **Encapsulation**: By being part of the class, static methods help encapsulate functionality that is logically related to the class but does not require access to instance-specific data.

### 2. **Access and Usage**
- **Access**: Static methods are called using the class name, reflecting their association with the class. This usage pattern reinforces their identity as methods within the class. Private static methods may be called from non-static methods of the same class, reinforcing the conceptual link between a static method and instances of its containing class.
- **Functionality**: Static methods can access other static methods and static variables of the class. This capability aligns with the class-level context and differentiates them from standalone functions.

### 3. **Terminological Consistency**
- **Method**: In OOP, the term *method* is used to describe functions that are defined within a class, regardless of whether they operate on instances or not. This convention maintains consistency in terminology.
- **Class Methods**: Similarly, class methods are also considered methods because they are associated with the class and can access class-level data and methods. Static methods fit this conceptual framework.

### Example to Illustrate the Concept
Here's a Python example to illustrate how static methods fit within a class:

```python
class MathUtility:
    # A static method
    @staticmethod
    def add(a, b):
        return a + b

    # Another static method
    @staticmethod
    def subtract(a, b):
        return a - b

# Calling static methods using the class name
result1 = MathUtility.add(5, 3)
result2 = MathUtility.subtract(10, 4)

print(result1)  # Output: 8
print(result2)  # Output: 6
```


Thus, even though static methods do not operate on instances, their definition within a class and their role in encapsulating class-related functionality justify their classification as methods rather than standalone functions.

## My opinion

I would argue that the link to an object or a class may be a bit too restrictive, when using the term *method*.

Consider expanding the context beyond objects and classes to include modules or namespaces. In many languages, modules or namespaces provide a way to group related functions and restrict their visibility from outside contexts. This grouping can enforce encapsulation and modularity in a manner similar to classes.

The key is understanding that what distinguishes a *method* from any other kind of function is the relation to some context as well as a visibility/accessibility specific to that context.

`Note that I do not further define what the kind of the relation should be, given that it may differ with many languages, and given that any further specification may not be general enough to be compatible with the constructs of all existing or future languages.`

For instance, in JavaScript or Python, functions defined within a module or namespace can be considered methods of that module if they are meant to operate within its context. These functions might not belong to a specific object or class, but they are still tied to the module's scope and restricted in their visibility and access.

Therefore, it might be appropriate to use the term _method_ instead of _function_ in such contexts. The essential characteristics that differentiate methods from functions—namely, the contextual association and restricted visibility—are present, but at the level of a module or namespace rather than an individual object or class.

By broadening our perspective, we can recognise that methods do not need to be limited to the traditional object-oriented paradigm. Instead, they can exist within any structured context that enforces scope and encapsulation, whether it be a class, module, or namespace.

## Summary
While, by definition, as methods are a special kind of function, both functions and methods perform similar roles by encapsulating code for reuse, methods are functions that live inside objects and are meant to operate on the data contained within those objects. Functions are more general-purpose and not tied to any particular data structure.