Pour Some Syntactic Sugar On Me: ‘Unless’ Keyword

Let’s face it, syntactic sugar can be a very attractive feature for a language (I consider Perl to be an extremely powerful language composed almost entirely of syntactic sugar), and I think it’s about time we all started demanding the “Unless” Keyword as a counterpart to the “If” Keyword. Let me give you a pretty common example:

if (    !ctype_digit($_POST['quantity']) 
    ||  !preg_match('/one of the billions of email address validators/',$_POST['email']) 
    ||  $_POST['password1'] != $_POST['password2'] 
    ||  !my_validation_routine($_POST['Im_Running_Out_Of_Examples'])
) {
    die('Bad Data');

Quick-And-Dirty form validation. Of course, one would normally want to check these separately so that meaningful error messages could be dumped, but let’s assume for a moment that this isn’t the case for this project. I’m not saying this is a life or death matter. I’m not saying the above code doesn’t work or anything like that. What I am saying is that, from a readability/logical perspective, it would make sense to have an unless keyword to transform the above sequence from a bunch of or-not ideas into and-must-be ideas. Example!

unless (    ctype_digit($_POST['quantity']) 
        &&  preg_match('/one of the billions of email address validators/',$_POST['email']) 
        &&  $_POST['password1'] == $_POST['password2'] 
        &&  my_validation_routine($_POST['Im_Running_Out_Of_Examples'])
) {
    die('Bad Data');

I realize some people don’t or won’t care about this, and that’s fine. It’s not for them. I like to think in code, and it would make code-thought to normal-though a bit more one-to-one if I could think in terms of “Unless a is valid and b is valid and c is valid return false” instead of “If a is not valid or b is not valid or c is not valid return false”. C++ Programmers are lucky in this regard, as they are 1 macro away from having this keyword:

#define unless(cond) if(!(cond))

In conclusion, I know it doesn’t really change any thing, I know some people don’t care, but I want it. I guess it’s time to start maintaining my own PHP distro…

Recent Entries

Comments are closed.