Functions in Object Oriented Programming

Sun, 05/28/2017 - 08:33

In mathematics a function in an operation where a variable is passed in an operation is performed and a result is returned.

x = f(n)

In OOP the concept is the same except that the function does not necessarily return a value.

var x = f(n);
/** 
 * @param type n
 * @return type
 * */
function f(n) {
     // operation  
     return n;
} 

In previous programming an operation that didn't return a value was known as a sub-procedure. This may still be the case in some languages however many modern OOP it makes more sense to simply return {void} ( or not return any value at all ). The function will still return a value of null. But that value isn't necessary to be acknowledged.

A function is useful to perform a repeated operation. It's a machine to do a task. When writing code, look at operations that are repeated. "what can be reduced into a function"?

Example:

a = b + c
d = e + f
g = h + i
A better way to accomplish these tasks might be:
a = func(b,c);
d = func(e,f);
g = func(h,i);
/** 
  * adds two integers
  * @param int a
  * @param int b
  * @return int
  * */
function func(a,b) {
     // add a to b and return the value
     return a + b;
}

NOTE: In this pseudo-code example data types are acknowledged only. Some higher languages don't require data-types to be declared, but it is always a good idea to acknowledge them in comments. Knowing the expected data-type helps when building and debugging and also helps to avoid type-juggling. Finally, in lower languages it helps to avoid data-type clashing.