Tuesday, 11 January 2022

Functional Terminology

Some terms in programming tend to confuse new programmers. There's a certain historical context to them, and with the rise of more recent technology, new terms muddy the waters a bit.

And among these terms are: function, subroutine and method. They all seem to be referring to the same thing - procedures - but there are some significant differences.

Today I will be attempting to provide some clarity.

Subprocedures

These are procedures that exist in a block of code, and can be called from anywhere. Arguments could be passed into them, optionally. In QBasic back in the day, there was a specific keyword for that.

SUB HELLOWORLD()
    PRINT "HELLO WORLD"
END SUB


CALL HELLOWORLD()


Basically, the subprocedure would perform whatever operations the programmer put in it, and that would be the end of it. This has all but vanished from the programming landscape. These days, it's all about functions, which we will examine below.

Functions

Functions are also procedures that exist in a block of code, and can be called from anywhere. Arguments could be passed into them, optionally. The difference is that after performing the operations, they return a value.

This is how it was done in QBasic or Visual Basic.

FUNCTION HELLOWOWLD(str)
    HELLOWORLD = str
END FUNCTION


PRINT HELLOWORLD("Hello world")


Or in JavaScript...
function helloWorld(str)
{
    return str;
}


console.log(helloWorld("Hello world"));


...and in certain cases may not even return anything.
function helloWorld(str)
{
    console.log(str);
}


helloWorld("Hello world");


So in these cases, a function works just like a subroutine, and thus subroutines are not really needed any more.

Methods

Now we come to methods. Methods are just like functions in every way... except for access control.

We call a function a method when it's part of an object. This is an example in JavaScript.
let obj =
{
    helloWorld: function (str)
    {
        console.log(str);
    }
}


So if we were to call this method, we can only call it when specifying the parent object.
obj.helloWorld("Hello world");


If we were to treat it like any other function, it would not work.
helloWorld("Hello world");


In some object-oriented programming languages such as Java or C++, if you specify that the class is Private (for instance), the method can only be called within the class itself. There's actually a fair bit to cover on this subject, but it's out of scope for this blogpost.

Finally()

As long as you have a clear idea of what you are referring to when you use these terms, end of the day it doesn't really matter what terms you use. Communication is key. Just don't be confused when the context changes, and the terms change with it. Ultimately, it's generally the same thing.

Play that func-y music!
T___T

No comments:

Post a Comment