Re: 'switch-expression' and the 'type guard' unary operator demo

From: Date: Mon, 21 Oct 2019 20:33:40 +0000
Subject: Re: 'switch-expression' and the 'type guard' unary operator demo
References: 1 2 3 4  Groups: php.internals 
Request: Send a blank email to internals+get-107615@lists.php.net to get a copy of this message
> On Oct 21, 2019, at 4:51 AM, Rowan Tommins <rowan.collins@gmail.com> wrote: > > On Sun, 20 Oct 2019 at 22:35, Mike Schinkel <mike@newclarity.net> wrote: >> I would much prefer to use a switch for multiple, mutually exclusive cases >> no matter what how complex the expression is because with a switch the >> cases expressions line up vertically. With if and >> else if it is harder >> to vertically eyeball the different mutually exclusive cases. > > I've never particularly been bothered by it, but wouldn't adding four > spaces in your "if" statement make it line up with all your "elseif" > statements? Possibly, but then again I am: 1) Mostly reading other people's code who will not have formatted their IFs that way, and 2.) Using a code reformatter to standardize code format via my IDE and there is no option for that. As for #1, I know I cannot enforce switch usage outside my own team, but at least for own team our standard says "use switch for multiple expressions" when possible so at least it would provide we can have consistency across our team. >> But how often will we have this use-case? Only for global variables, >> which hopefully will eventually become extinct in userland code. > > Not just global variables, no;... Fair point. >> That said, we should almost be able to do *both*, and just let PHP throw >> an error if there is a problem. This would be useful if you know 100% that >> the code won't fail because of the code that came before it: >> >> if ( is_numeric($_GET['id'] ?? 0 ) ) { >> $id = intvar($_GET['id'] ?? 0); >> $user = getUser(<int>$id): >> } > > I'm not sure what the point of this example is. You've just cast to int, so > the assertion can never fail, and if getUser has a type hint, it's about to > make that assertion anyway. Yeah, I know. I could not come up with a great example on the spot. I'll have to go off and do some more coding because that's when I always come across the good examples. Which is usually not the same time I need the good example. :-( -Mike

« previous php.internals (#107615) next »