On Aug 20, 2009, at 4:52 PM, Jason L. wrote:
Gary W. wrote:
and pre-conditions should be guaranteed by the caller,
not the callee. If pre-conditions aren’t met, then all bets
are off about how the callee will behave. Water under the bridge so
to speak.
Could you give me a simple example of guaranteeing pre-conditions by
the
caller? I’m having some trouble visualizing this. Thank you.
The simplest case is when the arguments are already known
to be numeric in which case you don’t have to do anything:
calculate_bounding_box(3.4, 5.6)
This would also be the case if you are calling from a method
with the same precondition (i.e. numeric arguments). The caller
is once again responsible for the arguments, not the intermediate
method:
def bigger_box(a,b)
calculate_bounding_box(2a,2b)
end
If you are getting the arguments from some untrustworthy source:
width, height = get_dodgy_dimensions()
if [width, height].all? { |x| Numeric === x }
box = calculate_bounding_box(width, height)
else
# report error, raise exception, etc.
end
The caller is in the best position to know what to
do if the arguments aren’t numeric (e.g. don’t call the method!).
If you get rid of the explicit test in my previous example:
width, height = get_dodgy_dimensions()
box = calculate_bounding_box(width, height)
It is clear from the name ‘get_dodgy_dimensions’ that this is
a really bad idea. That code is broken because it is passing
along unsanitized data. The solution isn’t to change
calculate_bounding_box to check its arguments but instead is
fix the source of the problem
width, height = get_dodgy_dimensions()
width, height = sanitize_dimensions(width, height)
box = calculate_bounding_box(width, height)
Gary W.