Skip to content

Instantly share code, notes, and snippets.

@valsteen
Last active November 9, 2020 11:36
Show Gist options
  • Save valsteen/857743e41c7ee30dca045c1a3d361381 to your computer and use it in GitHub Desktop.
Save valsteen/857743e41c7ee30dca045c1a3d361381 to your computer and use it in GitHub Desktop.
java enterprise ternary operator
package com.company;
/**
java -cp . com.company.Main "4" "3" "2"
4 is even
3 is not even
2 is even
*/
abstract class TernaryOperatorCondition<T> {
private T parameter;
private void setParameter(T x) {
parameter = x;
}
protected T getParameter() {
return parameter;
}
public TernaryOperatorCondition(T x) {
setParameter(x);
}
abstract boolean isTrue();
}
class TernaryOperatorResult<T> {
private T result;
private void setResult(T x) {
result = x;
}
public T getResult() {
return result;
}
public TernaryOperatorResult(T x) {
setResult(x);
}
}
class TernaryOperator<ResultType, ParameterType, TernaryOperatorParameterType extends TernaryOperatorCondition<ParameterType>> {
private ResultType result1;
private ResultType result2;
private void setResult1(ResultType x) {
result1 = x;
}
private ResultType getResult1() {
return result1;
}
private void setResult2(ResultType x) {
result2 = x;
}
private ResultType getResult2() {
return result2;
}
TernaryOperator(ResultType result1, ResultType result2) {
setResult1(result1);
setResult2(result2);
}
ResultType getResultFor(TernaryOperatorParameterType a) {
if (a.isTrue()) {
return getResult1();
} else {
return getResult2();
}
}
}
class TernaryOperatorFactory<ResultType, ParameterType> {
TernaryOperator<ResultType, ParameterType, TernaryOperatorCondition<ParameterType>> getTernaryOperator(ResultType x, ResultType y) {
return new TernaryOperator<>(x, y);
}
}
class IsEvenCondition extends TernaryOperatorCondition<Integer> {
public IsEvenCondition(Integer x) {
super(x);
}
@Override
boolean isTrue() {
return getParameter() % 2 == 0;
}
}
public class Main {
public static void main(String[] args) {
// build possible results
TernaryOperatorResult<String> isEven = new TernaryOperatorResult<>("is even");
TernaryOperatorResult<String> isNotEven = new TernaryOperatorResult<>("is not even");
// create the ternary operator
TernaryOperatorFactory<TernaryOperatorResult<String>, Integer> ternaryOperatorFactory = new TernaryOperatorFactory<>();
TernaryOperator<TernaryOperatorResult<String>, Integer, TernaryOperatorCondition<Integer>> ternaryOperator =
ternaryOperatorFactory.getTernaryOperator(isEven, isNotEven);
for (String arg : args) {
Integer x = Integer.parseInt(arg);
IsEvenCondition xIsEvenCondition = new IsEvenCondition(x);
String result = ternaryOperator.getResultFor(xIsEvenCondition).getResult();
System.console().writer().println(arg + " " + result);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment