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.

strager
  • 88,763
  • 26
  • 134
  • 176
  • Duplicate: http://stackoverflow.com/questions/77127/when-to-throw-an-exception – LiraNuna Nov 28 '09 at 00:53
  • 1
    @LiraNuna, It's not a duplicate. That question deals with user input validation; this deals with coder input validation. – strager Nov 28 '09 at 00:55
  • They are still the same. You expect a programmer to give you wrong input in a dynamic language. – LiraNuna Nov 28 '09 at 01:00
  • You should expect wrong input in a statically typed language too. The compiler can't catch every error. – Mark Byers Nov 28 '09 at 01:16
  • PHP is not Java with $'s, yet they do check and throw illegalargument execptions. I think the 'check your arguments' pattern is just as valid for function calls as for HTML form input. – Don Nov 28 '09 at 02:05

1 Answers1

3

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 Design by contract using assertions or exceptions?

Community
  • 1
  • 1
Jonathan Fingland
  • 56,385
  • 11
  • 85
  • 79
  • 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 Nov 28 '09 at 02:08
  • 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 Nov 28 '09 at 05:13