Is there a cleaner way to implement an "if not" condition check?

WHY NOT JUST USE "IF"?

For data validation, code is cleaner and more intelligible if the condition being checked is written in an affirmative sense; that is, in the same way that `assert` is written. This is especially true when `and` and `or` logic is involved. `if` is not a good substitute, because it works in the opposite sense, often requiring lots of `not`s. As a trivial example:

  assert( configfile.isFile && configfile.extension == ".conf" )
    -vs-
if ( !configfile.isFile || configfile.extension != ".conf" ) <handle it>

An `if` statement can be written in the affirmative sense, by using an empty `then` statement + an `else` statement:

if ( configfile.isFile && configfile.extension == ".conf", message ) { }
  else <handle it>

But then the logic intuitively feels wrong for an `if`, because the handler is always in the `else`. When there are only a few such checks, it might not matter. But when there are a lot of checks, the code gets ugly (lots of `else`s) and the clutter adds up.

ORIGINAL SOLUTION

The following solution works and the code is very readable. However, it has a couple of notable deficiencies.

  void unless(T)(T condition, lazy void func ) {
      if ( !condition ) func(); }
   :
unless( configfile.isFile && configfile.extension == ".conf", handleIt( _ _ ));

The most obvious shortcomings are:
1. It only works with a handler function. So `continue` and the like can't be used, for example. 2. It is inefficient, adding an extra function call to every condition check. Inside a loop, this is cumulative.

A BETTER SOLUTION ???

I haven't been able to come up with another option that is more efficient yet doesn't sacrifice readability. I would welcome suggestions.

Thanks in advance.
Denis

Reply via email to