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 java.io.Serializable;
20
21 import org.apache.commons.functor.Predicate;
22 import org.apache.commons.functor.Procedure;
23 import org.apache.commons.functor.core.NoOp;
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44 public final class ConditionalProcedure implements Procedure, Serializable {
45
46
47
48 private static final long serialVersionUID = -4228632798836328605L;
49
50
51 private static final int HASH_SHIFT = 4;
52
53
54
55 private final Predicate ifPred;
56 private final Procedure thenProc;
57 private final Procedure elseProc;
58
59
60
61
62
63
64
65
66 public ConditionalProcedure(Predicate ifPred, Procedure thenProc) {
67 this(ifPred, thenProc, NoOp.instance());
68 }
69
70
71
72
73
74
75
76 public ConditionalProcedure(Predicate ifPred, Procedure thenProc, Procedure elseProc) {
77 if (ifPred == null) {
78 throw new IllegalArgumentException("Predicate argument was null");
79 }
80 this.ifPred = ifPred;
81 if (thenProc == null || elseProc == null) {
82 throw new IllegalArgumentException("Procedure argument was null");
83 }
84 this.thenProc = thenProc;
85 this.elseProc = elseProc;
86 }
87
88
89
90
91
92
93 public void run() {
94 if (ifPred.test()) {
95 thenProc.run();
96 } else {
97 elseProc.run();
98 }
99 }
100
101
102
103
104 public boolean equals(Object that) {
105 return that == this || (that instanceof ConditionalProcedure && equals((ConditionalProcedure) that));
106 }
107
108
109
110
111
112
113 public boolean equals(ConditionalProcedure that) {
114 return null != that
115 && (null == ifPred ? null == that.ifPred : ifPred.equals(that.ifPred))
116 && (null == thenProc ? null == that.thenProc : thenProc.equals(that.thenProc))
117 && (null == elseProc ? null == that.elseProc : elseProc.equals(that.elseProc));
118 }
119
120
121
122
123 public int hashCode() {
124 int hash = "ConditionalProcedure".hashCode();
125 if (null != ifPred) {
126 hash <<= HASH_SHIFT;
127 hash ^= ifPred.hashCode();
128 }
129 if (null != thenProc) {
130 hash <<= HASH_SHIFT;
131 hash ^= thenProc.hashCode();
132 }
133 if (null != elseProc) {
134 hash <<= HASH_SHIFT;
135 hash ^= elseProc.hashCode();
136 }
137 return hash;
138 }
139
140
141
142
143 public String toString() {
144 return "ConditionalProcedure<" + ifPred + "?" + thenProc + ":" + elseProc + ">";
145 }
146
147 }