clean-code-php
clean-code-php copied to clipboard
Avoid type-checking rule ignores union or intersection type
Avoid type-checking doesn't address a realistic situation in which one might do type checking. If type declaration can be used that's great, but often it's not the case.
One major issue that PHP doesn't support union or intersection types.
/**
* @param \Traversable&\Countable $iterator
* @return \Generator
*/
function iterator_chop(\Traversable $iterator): \Generator
{
$piles = count($iterator); // Might not be countable
// ....
}
Again in the second example
/**
* @param int|float $val1
* @param int|float $val2
* @return int|float
*/
function combine($val1, $val2)
{
return $val1 + $val2; // Are these numbers?
}
In the second case, it's likely for the code to work without an error as first, but result in an unexpected error or, event worst, an unexpected result later.
No type checking goes against the "Fail fast" principle, which prevents you having to chase bugs through the code.
While static code analysis does a good job, it doesn't capture all issues.
The argument about it being to verbose isn't that strong, as you have many solutions to write it as one line. For instance with beberlei/assert.
This already exists RFC on this feature. Perhaps it will add to PHP 8.
@peter-gribanov On PHP8 we hopefully don't need manual type checking anymore. Until then we should not just "wing it".
Should I put in a PR?
@jasny i see the problem you described, but what solution do you offer? You can make a PR and we can discuss the problem there.