I am currently writing code and want to make sure all the params that get passed to a function/method are valid. Since I am writing in PHP I don’t have access to all the facilities of other languages like C, C++ or Java to check for parameters values and types
public function inscriptionExists($sectionId, $userId) // PHP
vs.
public boolean inscriptionExists(int sectionId, int userId) // Java
So I have to rely on exceptions if I want to make sure that my params are both integers.
Since I have a lot of places where I need to check for param validity, what would be the best way to create a validation/exception machine and avoid code duplication?
I was thinking on a static factory (since I don’t want to pass it to all of my classes) with a signature like:
public static function factory ($value, $valueType, $exceptionType = 'InvalidArgumentException');
Which would then call the right sub process to validate based on the type.
Am I on the right way, or am I going completely off the road and overthinking my problem?
2
PHP provides type hinting for objects and arrays. Unfortunately, not for scalar types such as string
or int
.
There are various approaches. One is to use assert statements :
public function inscriptionExists($sectionId, $userId){
assert(is_int($sectionId));
assert(is_int($userId));
}
One needs to ensure assert is active at least during development :
assert_options(ASSERT_ACTIVE, 1)
You could write a utility class along these lines
class Check{
public static function int(& $param, $name){
if( !is_int($param) ){
throw new InvalidArgumentException($name.' is not an integer');
}
}
}
and then
public function inscriptionExists($sectionId, $userId){
Check::int($sectionId, 'sectionId');
Check::int($userId, 'userId');
1
I think you are over-thinking your problem
In my opinion, dynamic typing is one of the features of PHP that makes it highly enjoyable to work with. Instead of enforcing strict typing rules, you can just document your function really well to indicate the parameters you expect. If the contract is not met, then results may vary and the fault is on the user of your function.
Plus if your code base is used only internally (by you and your team), you should have no problems with parameter types as you developped the code and should know how to use it. If your project is a library available to the public, good documentation is key. You should also have good unit tests to make sure your code behaves as expected and to provide examples on how to use your library.
I see you are trying to write Java code in PHP and that means that you still don’t understand PHP well. When writing code in a given language, you should try to embrace the language features/philosophy instead of looking back to what you already know and trying to adapt.
4