membersound
membersound

Reputation: 86747

How to typesafe check equality of booleans?

public class ComplexObject {
    private boolean isA, isB;
}

//custom comparator
public boolean checkComplexObject(ComplexObject o1, ComplexObject o2) {
   return o1.getIsA() == o2.getIsB();
}

Now when I change the data type in ComplexObject from boolean to String for example, the comparator will not break, nor will I notice that in future I would compare Strings instead of booleans and thus get different results.

Question: how could I compare the boolean properties typesafe, so that I get compilation error when I change the datatype of the fields?

Upvotes: 1

Views: 96

Answers (4)

Zhedar
Zhedar

Reputation: 3510

The better question is, why would you do that?

If you refactor (well, change heavily) your attributes from boolean to String you should always check the affected code. If you want code workarounds for a common practice (double checking), you're may introduce overly complicated code in your whole application.

If you're aware of that problem, why dont you put a comment directly on your affected class attributes, that it may be compared by ==. If you want or another dev wants to change it's type later on, they will be warned.

Upvotes: 0

Sidmeister
Sidmeister

Reputation: 856

You can use XOR for that:

return o1.getIsA() ^ o2.getIsB();

Upvotes: 0

Radiodef
Radiodef

Reputation: 37845

One very simple thing you can do is put in a redundant cast:

return (boolean)o1.getIsA() == (boolean)o2.getIsB();

You can also define a method that only accepts boolean:

static boolean booleanEquals(boolean a, boolean b) {
    return a == b;
}

Then call booleanEquals instead of using ==.


As a side note, this programming seems a bit overly defensive to me.

Upvotes: 3

Eran
Eran

Reputation: 393841

There are a few things you can do, but all of them will make your code less readable, and therefore I would advise against them.

For example :

return o1.getIsA() ^ o2.getIsB() == false;

or

return (o1.getIsA() && o2.getIsB()) ||  (!o1.getIsA() && !o2.getIsB());

Upvotes: 1

Related Questions