Military Smurf wrote:
"Larry Lard" wrote: - It's bad style to have 'side effects' in procedures, and worse to
have functions that consist _only_ of side effects! A call to this
function should be replaced with something like
_actualspeed = kph
_quote = DescribeSpeed(kph)
where DescribeSpeed takes an Integer and returns a String.
Thanks for that, and while I understand a lot of what you are saying, what
are these "side effects" I need to be aware of?
You can read more about side effects here:
<http://en.wikipedia.org/wiki/Side-effect_%28computer_science%29> but
in short, a side effect is when a function changes something that it
isn't obvious that it changes, typically a variable at some broader
scope. An example:
'module level
Dim a as integer
Function Negate(n as integer) as integer
Return -n
End Function
Function NegateWithSideEffect(n as integer) as integer
a = a + 1
Return -n
End Function
Sub Example()
Dim b as integer
b = 3
b = Negate(b)
'now b = -3 and no surprises
a = 2
b = NegateWithSideEffect(b)
'now b = 3 as expected
'BUT a has also changed!
End Sub
In this example, there is nothing to tell a caller of
NegateWithSideEffect that calling this function will also change a.
Real world examples don't have such 'giveaway' names! :)
There's a guideline for coding called the Principle of Least
Astonishment (more at
<http://en.wikipedia.org/wiki/Principle_of_least_astonishment>) which
basically says: don't do anything surprising. In this example changing
a might well come as a surprise, and an unpleasant one, to an unwitting
user of NegateWithSideEffect.
Like all guidelines and principles, how rigorously to stick to them
depends on a number of factors - throwaway programs for personal
consumption, you can get away with anything you like; flying a space
shuttle, get ten people to check every line. But in general it is
better to get into the habit of doing things 'the right way', so that
everything one does is better than it needs to be.
--
Larry Lard
Replies to group please