diff --git a/pmd-core/src/main/java/net/sourceforge/pmd/util/OptionalBool.java b/pmd-core/src/main/java/net/sourceforge/pmd/util/OptionalBool.java new file mode 100644 index 0000000000..861da469b6 --- /dev/null +++ b/pmd-core/src/main/java/net/sourceforge/pmd/util/OptionalBool.java @@ -0,0 +1,30 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.util; + +/** Represents a boolean that may not be present. Use as a non-null type. */ +public enum OptionalBool { + YES, NO, UNKNOWN; + + public OptionalBool complement() { + switch (this) { + case YES: return NO; + case NO: return YES; + default: return this; + } + } + + public boolean isKnown() { + return this != UNKNOWN; + } + + public boolean isTrue() { + return this == YES; + } + + public static OptionalBool definitely(boolean a) { + return a ? YES : NO; + } +} diff --git a/pmd-core/src/test/java/net/sourceforge/pmd/util/OptionalBoolTest.java b/pmd-core/src/test/java/net/sourceforge/pmd/util/OptionalBoolTest.java new file mode 100644 index 0000000000..44ec404c2e --- /dev/null +++ b/pmd-core/src/test/java/net/sourceforge/pmd/util/OptionalBoolTest.java @@ -0,0 +1,45 @@ +/* + * BSD-style license; for more info see http://pmd.sourceforge.net/license.html + */ + +package net.sourceforge.pmd.util; + +import static net.sourceforge.pmd.util.OptionalBool.NO; +import static net.sourceforge.pmd.util.OptionalBool.UNKNOWN; +import static net.sourceforge.pmd.util.OptionalBool.YES; +import static net.sourceforge.pmd.util.OptionalBool.definitely; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Test; + +public class OptionalBoolTest { + + @Test + public void testDefinitely() { + assertEquals(YES, definitely(true)); + assertEquals(NO, definitely(false)); + } + + @Test + public void testIsKnown() { + assertTrue(YES.isKnown()); + assertTrue(NO.isKnown()); + assertFalse(UNKNOWN.isKnown()); + } + + @Test + public void testIsTrue() { + assertTrue(YES.isTrue()); + assertFalse(NO.isTrue()); + assertFalse(UNKNOWN.isTrue()); + } + + @Test + public void testComplement() { + assertEquals(YES, NO.complement()); + assertEquals(NO, YES.complement()); + assertEquals(UNKNOWN, UNKNOWN.complement()); + } +}