Instantly share code, notes, and snippets.

Embed
What would you like to do?
Fluent API for comparing two Comparables.
public class ComparingUtils {
public static <T extends Comparable<T>> ComparisonBuilder<T> is(T comparable) {
return new ComparisonBuilder<>(comparable);
}
public static class ComparisonBuilder<T> {
private Comparable<T> subject;
private ComparisonBuilder(Comparable<T> subject) {
this.subject = subject;
}
public boolean greaterThan(T compared) {
return subject.compareTo(compared) > 0;
}
public boolean lessThan(T compared) {
return subject.compareTo(compared) < 0;
}
public boolean equalTo(T compared) {
return subject.compareTo(compared) == 0;
}
public boolean lessThanOrEqualTo(T compared) {
return lessThan(compared) || equalTo(compared);
}
public boolean greaterThanOrEqualTo(T compared) {
return greaterThan(compared) || equalTo(compared);
}
}
}
import org.junit.Test;
import java.math.BigDecimal;
import static ComparingUtils.is;
public class ComparingUtilsTest {
@Test
public void shouldReturnTrueWhenSubjectIsGreaterThanComparedUnlessReturnFalse() {
BigDecimal minusOne = BigDecimal.valueOf(-1);
BigDecimal zero = BigDecimal.ZERO;
assert is(zero).greaterThan(minusOne);
assert !is(minusOne).greaterThan(zero);
}
@Test
public void shouldReturnTrueWhenSubjectIsLessThanComparedUnlessReturnFalse() {
BigDecimal zero = BigDecimal.ZERO;
BigDecimal one = BigDecimal.ONE;
assert is(zero).lessThan(one);
assert !is(one).lessThan(zero);
}
@Test
public void shouldReturnTrueWhenSubjectIsEqualToComparedUnlessReturnFalse() {
BigDecimal tenThousands = BigDecimal.valueOf(10_000);
BigDecimal fiveThousands = BigDecimal.valueOf(5_000);
assert is(tenThousands).equalTo(new BigDecimal(10_000));
assert !is(tenThousands).equalTo(fiveThousands);
}
@Test
public void shouldReturnTrueWhenSubjectIsGreaterThanOrEqualToComparedUnlessReturnFalse() {
BigDecimal minusOne = BigDecimal.valueOf(-1);
BigDecimal zero = BigDecimal.ZERO;
BigDecimal one = BigDecimal.ONE;
assert is(zero).greaterThanOrEqualTo(zero);
assert is(zero).greaterThanOrEqualTo(minusOne);
assert !is(zero).greaterThanOrEqualTo(one);
}
@Test
public void shouldReturnTrueWhenSubjectIsLessThanOrEqualToComparedUnlessReturnFalse() {
BigDecimal minusOne = BigDecimal.valueOf(-1);
BigDecimal zero = BigDecimal.ZERO;
BigDecimal one = BigDecimal.ONE;
assert is(zero).lessThanOrEqualTo(zero);
assert is(zero).lessThanOrEqualTo(one);
assert !is(zero).lessThanOrEqualTo(minusOne);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment