tags:

views:

70

answers:

1

We are developing a collection class for a specialized PHP application. In it, there are functions named map, each, etc.

A debate has been brought up about calling some functions with a bad argument. For example:

public function each($fn) {
    // ...
}

// ...

$collection->each('not a function');

Should the call to each throw an exception? Should it return null? Should we ignore the bad argument and let the runtime error when an attempt is made to call the nonexistant function? I'm not sure how we should handle this case.

+3  A: 

exceptions are for exceptional situations, not bad coders.

Use assertions instead. See http://php.net/manual/en/function.assert.php

If this is for a library for external use, then exceptions on exposed methods may make sense, (e.g. InvalidArgumentException) but, in general, assertions are more appropriate for verifying internally that your code meets your required conditions.

Perhaps another example will help clarify things, a good use of an exception is when doing file access and as there is some possibility that the resource will not be accessible due to a downed server, etc.

Also see http://stackoverflow.com/questions/117171/design-by-contract-tests-by-assert-or-by-exception

Jonathan Fingland
design-by-contract-tests-by-assert-or-by-exception seems to say, use exceptions to report bad parameters -- especially in the interface method sense, where methods calls are much like HTML form input -- you always check that, don't you?
Don
bad html form input isn't really exceptional though... it's rather expected. handle it with an `if` and move on. exceptions aren't flow control.
Jonathan Fingland