From: Gary Wright Date: 2009-08-21T03:49:36+09:00 Subject: Re: extending ruby - handling errors On Aug 20, 2009, at 12:25 PM, Ben Giddings wrote: > > This is probably the wrong approach though. You shouldn't load up > "Object" so > it knows about random other methods that it's subclasses define, you > should > just catch NoMethodError in an appropriate spot. For example: > > def calculate_bounding_box(width, height) > begin > width_bound = width.ceil > height_bound = height.ceil > rescue NoMethodError > raise ArgumentError, "width and height must be numeric" > end > width_bound * height_bound > end I would argue that this is also the wrong approach because it confuses responsibilities. To use programming by contract terminology, the requirement that the actual arguments to calculate_bounding_box be numeric (or more specifically that they respond to ceil) is a pre-condition 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. Also, the example as written doesn't really solve the problem since the caller will have to deal with ArgumentError instead of NoMethodError. In either case it indicates that the *caller* is shirking its duty to guarantee the pre-conditions. Adding code in the caller to guarantee numeric arguments is probably clearer than arranging to respond to NoMethodError or ArgumentError. The correct solution is to fix the buggy code that is *calling* calculate_bounding_box to guarantee the pre-condition. Gary Wright