1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.functor.core.composite;
18
19 import org.apache.commons.functor.BinaryPredicate;
20 import org.apache.commons.functor.BinaryProcedure;
21 import org.apache.commons.functor.core.NoOp;
22 import org.apache.commons.lang3.Validate;
23
24
25
26
27
28
29
30
31
32
33
34
35
36 public final class ConditionalBinaryProcedure<L, R> implements BinaryProcedure<L, R> {
37
38
39 private static final int HASH_SHIFT = 4;
40
41
42
43
44
45 private final BinaryPredicate<? super L, ? super R> ifPred;
46
47
48
49 private final BinaryProcedure<? super L, ? super R> thenProc;
50
51
52
53 private final BinaryProcedure<? super L, ? super R> elseProc;
54
55
56
57
58
59
60
61
62
63 public ConditionalBinaryProcedure(BinaryPredicate<? super L, ? super R> ifPred,
64 BinaryProcedure<? super L, ? super R> thenProc) {
65 this(ifPred, thenProc, NoOp.instance());
66 }
67
68
69
70
71
72
73
74 public ConditionalBinaryProcedure(BinaryPredicate<? super L, ? super R> ifPred,
75 BinaryProcedure<? super L, ? super R> thenProc, BinaryProcedure<? super L, ? super R> elseProc) {
76 this.ifPred = Validate.notNull(ifPred, "BinaryPredicate argument was null");
77 this.thenProc = Validate.notNull(thenProc, "'then' BinaryProcedure argument was null");
78 this.elseProc = Validate.notNull(elseProc, "'else' BinaryProcedure argument was null");
79 }
80
81
82
83
84
85
86
87 public void run(L left, R right) {
88 if (ifPred.test(left, right)) {
89 thenProc.run(left, right);
90 } else {
91 elseProc.run(left, right);
92 }
93 }
94
95
96
97
98 @Override
99 public boolean equals(Object obj) {
100 if (obj == this) {
101 return true;
102 }
103 if (!(obj instanceof ConditionalBinaryProcedure<?, ?>)) {
104 return false;
105 }
106 ConditionalBinaryProcedure<?, ?> that = (ConditionalBinaryProcedure<?, ?>) obj;
107 return this.ifPred.equals(that.ifPred)
108 && this.thenProc.equals(that.thenProc)
109 && this.elseProc.equals(that.elseProc);
110 }
111
112
113
114
115 @Override
116 public int hashCode() {
117 int hash = "ConditionalBinaryProcedure".hashCode();
118 hash <<= HASH_SHIFT;
119 hash ^= ifPred.hashCode();
120 hash <<= HASH_SHIFT;
121 hash ^= thenProc.hashCode();
122 hash <<= HASH_SHIFT;
123 hash ^= elseProc.hashCode();
124 return hash;
125 }
126
127
128
129
130 @Override
131 public String toString() {
132 return "ConditionalBinaryProcedure<" + ifPred + "?" + thenProc + ":" + elseProc + ">";
133 }
134 }