Skip to content

Commit 5881969

Browse files
committed
tidy up Condition a bit, and prevent sub-classing.
1 parent 2954dce commit 5881969

File tree

1 file changed

+29
-16
lines changed

1 file changed

+29
-16
lines changed

hamcrest-core/src/main/java/org/hamcrest/Condition.java

Lines changed: 29 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,12 @@ public interface Step<I, O> {
1717
Condition<O> apply(I value, Description mismatch);
1818
}
1919

20-
public boolean matching(Matcher<T> match) { return matching(match, ""); }
20+
private Condition() { }
21+
2122
public abstract boolean matching(Matcher<T> match, String message);
2223
public abstract <U> Condition<U> and(Step<? super T, U> mapping);
24+
25+
public final boolean matching(Matcher<T> match) { return matching(match, ""); }
2326
public final <U> Condition<U> then(Step<? super T, U> mapping) { return and(mapping); }
2427

2528
@SuppressWarnings("unchecked")
@@ -28,25 +31,35 @@ public static <T> Condition<T> notMatched() {
2831
}
2932

3033
public static <T> Condition<T> matched(final T theValue, final Description mismatch) {
31-
return new Condition<T>() {
32-
@Override
33-
public boolean matching(Matcher<T> matcher, String message) {
34-
if (matcher.matches(theValue)) {
35-
return true;
36-
}
37-
mismatch.appendText(message);
38-
matcher.describeMismatch(theValue, mismatch);
39-
return false;
40-
}
34+
return new Matched<T>(theValue, mismatch);
35+
}
36+
37+
private static final class Matched<T> extends Condition<T> {
38+
private final T theValue;
39+
private final Description mismatch;
4140

42-
@Override
43-
public <U> Condition<U> and(Step<? super T, U> next) {
44-
return next.apply(theValue, mismatch);
41+
private Matched(T theValue, Description mismatch) {
42+
this.theValue = theValue;
43+
this.mismatch = mismatch;
44+
}
45+
46+
@Override
47+
public boolean matching(Matcher<T> matcher, String message) {
48+
if (matcher.matches(theValue)) {
49+
return true;
4550
}
46-
};
51+
mismatch.appendText(message);
52+
matcher.describeMismatch(theValue, mismatch);
53+
return false;
54+
}
55+
56+
@Override
57+
public <U> Condition<U> and(Step<? super T, U> next) {
58+
return next.apply(theValue, mismatch);
59+
}
4760
}
4861

49-
private static class NotMatched<T> extends Condition<T> {
62+
private static final class NotMatched<T> extends Condition<T> {
5063
@Override public boolean matching(Matcher<T> match, String message) { return false; }
5164

5265
@Override public <U> Condition<U> and(Step<? super T, U> mapping) {

0 commit comments

Comments
 (0)