Search code examples
javapropertiesconventions

Reverse the value of a boolean property


I have an (Java) object backed by a database table. In the database, a value of "N" in a (new)column implies something is forbidden, while a value of "Y" or null (default) implies that something is allowed.

In my object, I'm looking to have the same effect: by default forbidden = false, but it can be set to true, if desired. I'm working with existing code, so I don't want to modify the constructor.

However, the way the property will be used is likely to be (and I think is more understandable) is positive: isAllowed()/setAllowed(). I have therefore set up my code as:

public boolean isAllowed()
{   return !this.forbidden;  }
public void setAllowed(boolean allowed)
{   this.forbidden = ! allowed;  }
  1. Does anyone else consider if ([!]isAllowed()) {...} to be more understandable than if ([!]isForbidden()) {...}, or am I making an erroneous assumption?
  2. Does my code make sense? (Yes, I'm trying to comment it properly, that's why I'm asking.)
  3. My main question: Is there a conventional name for this kind of tweak? A boolean property backed by a field that carries the opposite value of the exposed property.

Thank you.


Solution

  • (1) Does anyone else consider if ([!]isAllowed()) {...} to be more understandable than if ([!]isForbidden()) {...}...

    Yes. Positives are usually the way to go. Not always, but usually. Consider the case where code wants to branch on whether something is allowed:

    if (something.isAllowed()) {
        // do the thing
    }
    

    vs.

    if (!something.isForbidden()) {
       // do the thing
    }
    

    The first just reads a lot more fluidly. (But this is subjective.)

    Just FWIW, I'd probably hold the data member as allowed rather than forbidden, too. So you wouldn't be inverting it in the accessor. Because the argument above applies just as much to code that uses the field directly (assuming you have code that does) as to code using the accessor.

    (2) Does my code make sense?

    Other than the bracing style, yes. :-) (And style is just style, and completely your own decision.)

    (3) - My main question: Is there a conventional name for this kind of tweak?

    I've never heard one, it's not really common enough. I suppose you're doing something vaguely facade or adapter-like, but it's a real stretch. :-)