Re: What do we need strict scalar type hints for?

From: Date: Tue, 03 Feb 2015 20:51:50 +0000
Subject: Re: What do we need strict scalar type hints for?
References: 1 2 3 4 5 6  Groups: php.internals 
Request: Send a blank email to internals+get-81740@lists.php.net to get a copy of this message
Hi all, On Wed, Feb 4, 2015 at 5:23 AM, Thomas Bley <mails@thomasbley.de> wrote: > function addVat($amount) { > validateAmount($amount); > return round($amount*1.19, 2); > } > > function validateAmount($amount) { > if (!is_int($amount) && !is_float($amount)) { > throw new InvalidArgumentException('Argument amount must be of the > type int|float, '.gettype($amount).' given'); > } > } > I use such code where runtime check is required. I prefer following for better performance/readability. i.e. Pre/Post conditions are inside of function definition. If PHP supports native DbC, runtime checks are omitted and script runs faster. NOTE: Dev time checks are done in in/out block with proper DbC design. Runtime check should be in function body. function addVat($amount) in { // precondition check assert(!is_int($amount) && !is_float($amount)); // OR if (!is_int($amount) && !is_float($amount)) { throw new InvalidArgumentException('Argument amount must be of the type int|float, '.gettype($amount).' given'); } } out { // postcondition check assert(is_numeric($__return_vlaue) && $__return_value > 0 && $__return_value < MAX_AMOUNT); } { // function body return round($amount*1.19, 2); } Type hints are useful for simple runtime check. Much less lines to write ;) It also encourage users to validate their app inputs. This is important benefits for secure apps. Things like these encourage proper DbC design naturally. Therefore, I'm +1 for all of these. Regards, -- Yasuo Ohgaki yohgaki@ohgaki.net

« previous php.internals (#81740) next »