Reputation: 12552
I know the title seems enigmatic, and maybe it is. It's almost a dilemma. I'm developing a framework for study purposes (and possibly professional), and I then intend to jointly develop a documentation explaining all the properties and methods in the project.
The documentation should explain that the sum()
method must take two integer arguments. For example:
/**
* Sum two numbers.
* @param int $a
* @param int $b
* @return int
*/
function sum($a, $b) {
return $a + $b;
}
But the question is, if by any chance the user John Doe decide to send the wrong kind of information (whatever why, maybe because they do not read the documentation), how should I handle the error? Should I let PHP get the job (which in some cases can run the code with perfection, coincidentally), or do a manual check and throw my own error, so that the coincidence can not occur? For example:
function sum($a, $b) {
throwErrorIfNotMatchType($a, "int");
throwErrorIfNotMatchType($b, "string");
return $a + $b;
}
In short, the responsibility to control errors and coincidences must be managed entirely by the API, or full responsibility for the user (who should have read the existing documentation), or should be controlled partially? In the case of the last answer on what occasions?
Upvotes: 0
Views: 30
Reputation: 65324
Type checking costs CPU - that is a fact. So you need to chose your poison
Some APIs chose to offer both and let the consumer chose the poison, here is what I mean:
/**
* Sum two numbers, without checking types.
* @param int $a
* @param int $b
* @return int
*/
function sum($a, $b) {
return $a + $b;
}
/**
* Sum two numbers, throw if checking types fails
* @param int $a
* @param int $b
* @return int
*/
function ts_sum($a, $b) {
throwErrorIfNotMatchType($a, "int");
throwErrorIfNotMatchType($b, "int");
return sum($a, $b);
}
Now the smart part is, that it will be quite feasable, to automatically generate the second version from the first version plus doc comments.
Upvotes: 1