Search code examples
javascriptcomputer-science

Arity of methods


When classifying the arity of a method function, do you need to consider the use of this? For example:

// Unary
function double(num) {
    return num * 2;
}

// Binary
function add(num1, num2) {
    return num1 + num2;
}

class Calc {
    value;

    // Unary or binary?
    add(num1) {
        return this.value + num1;
    }

    // Nullary or unary?
    double() {
        return this.value * 2;
    }
}

I've always thought of this as an implicit parameter.

(I'm assuming there is a language-agnostic answer to this, but it's JavaScript I'm most interested in the answer to)


Solution

  • C++ and other OOP languages allow us to write something like this:

    C a,b,c;
    c = a + b;
    

    (C is a class, a, b and c are instances of class C)

    The class C can define the + operator either as a method or as a friend function. As a method it accepts one argument (it is the second operand, the first operand is this). As a friend function it requires two arguments (the two operands).

    The addition is a binary operator (we know this from mathematics and the usage above cannot deny this). The fact that in C++ it can be implemented as a method that accepts only one explicit argument is just an implementation detail. Its actual arity is set by the number of values it requires to be used.

    The bottom line is: this must be counted as an argument. If the function does not use it then it should not be an instance method but a class method or an independent function.