Tip:
Highlight text to annotate it
X
In this lesson, I want to address a very important principle about writing functions, and that is in every function should have its singular task that it
is to perform and nothing else besides that. You're very tempted sometimes to put extraneous operations
in a function concerned with some particular operation.
Here is an example. Suppose that you want to write a function
that is to calculate a square root.
what can you take a square root of? You can only take the square root of non-negative numbers.
so should the process of routing out, no pun intended, negative numbers to be taken square root be part of that
function? And the answer is no.
Should entering of data, to take the square root be part of that function? And the answer is no.
Should there be some provision in the function that if it's sent a negative number, that
the function should bail? And answer is, no.
The function should find the square root of the value sent, and that's it. Nothing more. There should be no
if, there should be no prompting and reading in. There should only be the code that is going to calculate the square root.
Well, I don't have that here, of course if I were to write it, I would use Newton's method.
I don't need to write it, of course. The square root function is part of the math library.
But, the point is,
that should be the duty of the function and nothing else.
Another example. To go back to our previous lesson where we calculated the volume of the cylinder. Should part of
that function be to query the user for the radius? No.
That should be done in the calling function, just like I have here. Where
it’s in the calling function that we obtain the number to be taken,
the square root of and then we'll find the square root of that number.
That is not the purview of
that function to calculate the volume of a cylinder.
That's the concept.