Consider a code, where I need to find square of sum of x
largest elements in an array. ( this is NOT a which data structure question, so please dont post replies recommending heap etc.).
I initially code it up :
OPTION1
singleFunction {
// code to sort
// code to sum
// code to sqaure
return;
}
Soon, I realize I could leverage helper functions and break them into functions.
OPTION 2
getFinalAnswer() {
// sort;
return sumAndSquare();
}
sumAndSqaure() {
// sum
return square();
}
square() {
// return square.
}
Now I realize sort, sum and square can be used as utility methods
rather than simply helper
methods.
Now I break down functionality into 3 functions (1) sort (2) sum x (3) square()
OPTION3
someFunction(int[] arr, int x) {
sort(arr);
b = sumOfLastXElements(arr, x);
c = sqaure(b);
return c;
}
Now questions:
Looks like option 3 is the best of the lot, still so many times we find a function calling another. What is an advantage of option 2 over option 3 ?
A method by definition is supposed to do a single task/responsibility. but
somefunction
is doing 3 different things. What are such functions called ?