3

I'm trying to figure out what's better approach for argument passing to the class methods / standard functions.

Basically - if we use default null for each argument then we can validate them from within the method and throw an exception, but if we do not assign any default value to them and no argument has been passed when the method is called it will throw an Error.

My question is - which one is the more 'correct' approach:

public function getOne($id = null) {

    if (empty($id)) {

        throw new Exception('Method '.__METHOD__.' failed : invalid argument');

    }

    // throws an exception if no argument is passed

}

vs:

public function getOne($id) {

    // throws an error if no argument is passed

}

The first approach allows me to catch the exception and return relevant output, wheres (and I might be wrong here) Error does not provide this sort of functionality.

Also - is it better to hint object instance arguments with the class name or pass it as standard argument and check whether it's an instance of the given object - pretty much same situation:

public function getOne($mdlUser = null) {

    if (
        is_object($mdlUser) &&
        $mdlUser instanceof 'UserModel'
    ) {

        throw new Exception('Method '.__METHOD__.' failed : invalid argument');

    }

    // throws an exception if no argument is passed

}

vs:

public function getOne(UserModel $mdlUser) {

    // throws an error if no argument is passed

}

I would like to hear some opinions / facts including pros and cons of both.

Spencer Mark
  • 5,263
  • 9
  • 29
  • 58
  • Calling a function the wrong way (e.g. missing required arguments) is simply fundamentally broken code. I don't know why this should be a catchable exception in the first place. It's an error on the same level as invalid syntax, not something that should conditionally be handled. – deceze Aug 02 '14 at 12:04
  • 1
    That's what I though, but the fact that Exceptions give you more flexibility in the way you can handle this sort of situations led me to think that perhaps exception way is a better approach. The best example would be a controller method that wraps the code with try / catch statement, and if for any reason, any of the methods called within the try block has thrown exception - you can format the nice message etc. wheres with Error you will simply get the default error page. That said - I still agree with you that probably required arguments should not have default 'null' assigned to them. – Spencer Mark Aug 02 '14 at 12:20
  • You can and should configure actual error pages in your hosting web server. It doesn't have to be the "default" error page. – deceze Aug 02 '14 at 14:22

0 Answers0