[Pharo-users] Defensive programming or not

Sven Van Caekenberghe sven at stfx.eu
Mon Sep 23 04:51:36 EDT 2019


Hi Kasper,

> On 23 Sep 2019, at 10:18, Kasper Osterbye <kasper.osterbye at gmail.com> wrote:
> 
> Cheers all,
> 
> In trying to fix one of the issues in Pharo, I came to wonder about the prefered style in in dealing with preconditions to methods in Pharo.
> 
> In the method Random>>nextInt: anInteger
> 	• There is a check if anInteger is negative
> 	• There is no check that anInteger is anInteger
> When should I put a guard there, and throw an early warning, and when is it part of the (often implicit pre-condition)?
> 
> Best,
> 
> Kasper

This is very good question.

In my opinion, in a dynamically typed language you should not explicitly enforce all types. 

It is OK to rely on MessageNotUnderstood exceptions, it is the ultimate protection.

Of course, you could help your users/callers by throwing more useful exceptions, when that makes sense.

There is also a cost with checking (too often).

Furthermore, #isInteger or #isString are close testing the for a class, which is not considered good object design.

In the case of Random>>nextInt: speed seems important, but a robust interface with type checking has some value too. Hard to decide.

Sven





More information about the Pharo-users mailing list