Options/enums in java? - java

Is there a best practice for enumerations in java? For example, I have the following:
class Foo {
public static final int OPTION_1 = 'a';
public static final int OPTION_2 = 'b';
public void doSomething(String name, int option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.doSomething("blah", Foo.OPTION_2);
}
so the user can choose to use one of the static ints defined in Foo, but they could also supply any other int they want, there's no compile-time checking on it. Is there some way around this in java, some other way of doing this to restrict the end developer to choose from only the defined option types?
Thanks

class Foo {
public enum Option{First, Second}
public void doSomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.dosomething("blah", Foo.Option.Second);
}

Since Java 1.5 there is the enum keyword which makes typesafe enumerations
Your code would look like this then :
class Foo {
public enum Option = { OPTION_1, OPTION_2 };
public void doSomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.doSomething("blah", Foo.Option.OPTION_2);
}
This is fully supported by the type system so the compiler will enforce the user not to become to creative when passing options.
You can read more here

There are enum types in Java (as of J2SE 5.0). Read the tutorial.
public enum Option{
OPTION_1, OPTION_2 //All caps by convention
}
class Foo {
public void dosomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.dosomething("blah", Option.OPTION_2);
}

you even can add method into enum, check it out at sun document http://download.oracle.com/javase/tutorial/java/javaOO/enum.html

This will allow you to set the value of the enum
enum Option{
ONE('a');
TWO('b');
private Option(int x){
value = x;
}
private int value;
}
class Foo {
public void doSomething(String name, Option option) {
...
}
}
void test() {
Foo foo = new Foo();
foo.dosomething("blah", Option.ONE);
}

Related

What is the idiomatic way to write common code for a group of classes with identical methods, but not implementing the same interface?

I'm using an external library that provides tightly related classes (generated from some template), but unfortunately without a shared interface, e.g.
public class A {
public UUID id();
public Long version();
public String foo();
public String bar();
}
public class B {
public UUID id();
public Long version();
public String foo();
public String bar();
}
public class C {
public UUID id();
public Long version();
public String foo();
public String bar();
}
// ... and more: D, E, F, etc.
Given I have no influence over the external library, what's the idiomatic way to write logic common to a group of classes that share the same method signatures (at least, for the methods being used by the common logic)?
Currently I do one of three things, on a case-by-case basis:
I write helper methods that take the primitive results from each object, e.g.
private static void myHelper(UUID id, Long version, String foo, String bar) {
...
}
This way I can "unpack" an object regardless of its type:
myHelper(whatever.id(), whatever.version(), whatever.foo(), whatever.bar());
But that can get very wordy, especially when I need to work with many members.
In the scenario where I'm only working with getters (i.e. only need to access current values of the objects), I've found a way to use mapping libraries like Dozer or ModelMapper to map A or B or C to my own common class, e.g.
public class CommonABC {
UUID id;
Long version;
String foo;
String bar;
}
By playing with configuration, you can get these libraries to map all members, whether method or field, public or private, to your class, e.g.
modelMapper.getConfiguration()
.setFieldMatchingEnabled(true)
.setFieldAccessLevel(Configuration.AccessLevel.PRIVATE);
But this was kind of a "broadsword" approach, a hack that IMO isn't clearly justified merely to factor out duplicate code.
Finally, in certain other scenarios it was most succinct to simply do
private static void myHelper(Object extLibEntity) {
if (extLibEntity instanceof A) {
...
} else if (extLibEntity instanceof B) {
...
} else if (extLibEntity instanceof C) {
...
} else {
throw new RuntimeException(...);
}
}
It's obvious why this is bad.
In enterprise situations where you have to live with a library that is this way, what would you do?
I'm leaning toward writing a very explicit, if verbose, mapper (not using a generic mapper library) that translates these entities from the start. But, I wonder if there's a better way. (Like, is there a way to "cast" an object as implementing a new interface, in runtime?)
An option that is (under the hood) likely similar to the second approach, but comparatively lean and flexible, is to use Dynamic Proxy Classes. With only a few lines of code, you can let any object "appear" to implement a certain interface, as long as it has the required methods. The following is an MCVE that shows the basic approach:
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.UUID;
public class DelegatingProxyExample {
public static void main(String[] args) {
A a = new A();
B b = new B();
C c = new C();
CommonInterface commonA = wrap(a);
CommonInterface commonB = wrap(b);
CommonInterface commonC = wrap(c);
use(commonA);
use(commonB);
use(commonC);
}
private static void use(CommonInterface commonInterface) {
System.out.println(commonInterface.id());
System.out.println(commonInterface.version());
System.out.println(commonInterface.foo());
System.out.println(commonInterface.bar());
}
private static CommonInterface wrap(Object object) {
CommonInterface commonInterface = (CommonInterface) Proxy.newProxyInstance(
CommonInterface.class.getClassLoader(),
new Class[] { CommonInterface.class }, new Delegator(object));
return commonInterface;
}
}
// Partially based on the example from
// https://docs.oracle.com/javase/8/docs/technotes/guides/reflection/proxy.html
class Delegator implements InvocationHandler {
private static Method hashCodeMethod;
private static Method equalsMethod;
private static Method toStringMethod;
static {
try {
hashCodeMethod = Object.class.getMethod("hashCode", (Class<?>[]) null);
equalsMethod = Object.class.getMethod("equals", new Class[] { Object.class });
toStringMethod = Object.class.getMethod("toString", (Class<?>[]) null);
} catch (NoSuchMethodException e) {
throw new NoSuchMethodError(e.getMessage());
}
}
private Object delegate;
public Delegator(Object delegate) {
this.delegate = delegate;
}
public Object invoke(Object proxy, Method m, Object[] args) throws Throwable {
Class<?> declaringClass = m.getDeclaringClass();
if (declaringClass == Object.class) {
if (m.equals(hashCodeMethod)) {
return proxyHashCode(proxy);
} else if (m.equals(equalsMethod)) {
return proxyEquals(proxy, args[0]);
} else if (m.equals(toStringMethod)) {
return proxyToString(proxy);
} else {
throw new InternalError("unexpected Object method dispatched: " + m);
}
} else {
// TODO Here, the magic happens. Add some sensible error checks here!
Method delegateMethod = delegate.getClass().getDeclaredMethod(
m.getName(), m.getParameterTypes());
return delegateMethod.invoke(delegate, args);
}
}
protected Integer proxyHashCode(Object proxy) {
return new Integer(System.identityHashCode(proxy));
}
protected Boolean proxyEquals(Object proxy, Object other) {
return (proxy == other ? Boolean.TRUE : Boolean.FALSE);
}
protected String proxyToString(Object proxy) {
return proxy.getClass().getName() + '#' + Integer.toHexString(proxy.hashCode());
}
}
interface CommonInterface {
UUID id();
Long version();
String foo();
String bar();
}
class A {
public UUID id() {
return UUID.randomUUID();
}
public Long version() {
return 1L;
}
public String foo() {
return "fooA";
}
public String bar() {
return "barA";
}
}
class B {
public UUID id() {
return UUID.randomUUID();
}
public Long version() {
return 2L;
}
public String foo() {
return "fooB";
}
public String bar() {
return "barB";
}
}
class C {
public UUID id() {
return UUID.randomUUID();
}
public Long version() {
return 3L;
}
public String foo() {
return "fooC";
}
public String bar() {
return "barC";
}
}
Of course, this uses reflection internally, and should only be used when you know what you're doing. Particularly, you should add some sensible error checking, at the place that is marked with TODO: There, the method of the interface is looked up in the given delegate object.
The only technique not tried:
package aplus;
public interface Common {
...
}
public class A extends original.A implements Common {
}
public class B extends original.B implements Common {
}

Java Enum one to one to another Enum [duplicate]

Is there a way to get around the class-loading issues caused by having two enums that reference each other?
I have two sets of enumerations, Foo and Bar, defined like so:
public class EnumTest {
public enum Foo {
A(Bar.Alpha),
B(Bar.Delta),
C(Bar.Alpha);
private Foo(Bar b) {
this.b = b;
}
public final Bar b;
}
public enum Bar {
Alpha(Foo.A),
Beta(Foo.C),
Delta(Foo.C);
private Bar(Foo f) {
this.f = f;
}
public final Foo f;
}
public static void main (String[] args) {
for (Foo f: Foo.values()) {
System.out.println(f + " bar " + f.b);
}
for (Bar b: Bar.values()) {
System.out.println(b + " foo " + b.f);
}
}
}
The above code produces as output:
A bar Alpha
B bar Delta
C bar Alpha
Alpha foo null
Beta foo null
Delta foo null
I understand why it happens - the JVM starts classloading Foo; it sees the Bar.Alpha in Foo.A's constructor, so it starts classloading Bar. It sees the Foo.A reference in the call to Bar.Alpha's constructor, but (since we're still in Foo.A's constructor) Foo.A is null at this point, so Bar.Alpha's constructor gets passed a null. If I reverse the two for loops (or otherwise reference Bar before Foo), the output changes so that Bar's values are all correct, but Foo's values are not.
Is there any way to get around this? I know I can create a static Map and a static Map in a 3rd class, but that feels fairly hackish to me. I could also make Foo.getBar() and Bar.getFoo() methods that refer to the external map, so it wouldn't even change my interface (the actual classes I have use inspectors instead of public fields), but it still feels kind of unclean to me.
(The reason I'm doing this in my actual system: Foo and Bar represent types of messages that 2 apps send to each other; the Foo.b and Bar.f fields represent the expected response type for a given message - so in my sample code, when app_1 receives a Foo.A, it needs to reply with a Bar.Alpha and vice-versa.)
Thanks in advance!
One of the best ways would be using the enum polymorphism technique:
public class EnumTest {
public enum Foo {
A {
#Override
public Bar getBar() {
return Bar.Alpha;
}
},
B {
#Override
public Bar getBar() {
return Bar.Delta;
}
},
C {
#Override
public Bar getBar() {
return Bar.Alpha;
}
},
;
public abstract Bar getBar();
}
public enum Bar {
Alpha {
#Override
public Foo getFoo() {
return Foo.A;
}
},
Beta {
#Override
public Foo getFoo() {
return Foo.C;
}
},
Delta {
#Override
public Foo getFoo() {
return Foo.C;
}
},
;
public abstract Foo getFoo();
}
public static void main(String[] args) {
for (Foo f : Foo.values()) {
System.out.println(f + " bar " + f.getBar());
}
for (Bar b : Bar.values()) {
System.out.println(b + " foo " + b.getFoo());
}
}
}
The above code produces the output you want:
A bar Alpha
B bar Delta
C bar Alpha
Alpha foo A
Beta foo C
Delta foo C
See also:
Overridding method of a specific enum
The issue isn't so much "two enums reference each other", it's more "two enums reference each other in their constructors". This circular reference is the tricky part.
How about using Foo.setResponse(Bar b) and Bar.setResponse(Foo f) methods? Instead of setting a Foo's Bar in the Foo constructor (and similarly a Bar's Foo in the Bar constructor), you do the initialization using a method? E.g.:
Foo:
public enum Foo {
A, B, C;
private void setResponse(Bar b) {
this.b = b;
}
private Bar b;
public Bar getB() {
return b;
}
static {
A.setResponse(Bar.Alpha);
B.setResponse(Bar.Delta);
C.setResponse(Bar.Alpha);
}
}
Bar:
public enum Bar {
Alpha, Beta, Delta;
private void setResponse(Foo f) {
this.f = f;
}
private Foo f;
public Foo getF() {
return f;
}
static {
Alpha.setResponse(Foo.A);
Beta.setResponse(Foo.C);
Delta.setResponse(Foo.C);
}
}
Also, you mention that Foo and Bar are two types of messages. Would it be possible to combine them into a single type? From what I can see, their behavior here is the same. This doesn't fix the circular logic, but it might give you some other insight into your design...
Since it seems you're going to be hard-coding anyways, why not have something like
public static Bar responseBar(Foo f) {
switch(f) {
case A: return Bar.Alpha;
// ... etc
}
}
for each enum? It looks like you have some overlapping responses in your example, so you could even take advantage of cases falling through.
EDIT:
I like Tom's suggestion of the EnumMap; I think performance is probably faster on the EnumMap, but the sort of elegant construction described in Effective Java doesn't seem to be afforded by this particular problem - however, the switch solution offered above would be a good way to construct two static EnumMaps, then the response could be something like:
public static Bar response(Foo f) { return FooToBar.get(f); }
public static Foo response(Bar b) { return BarToFoo.get(b); }
Interesting design. I see your need, but what are you going to do when the requirements shift slightly, so that in response to Foo.Epsilon, app_1 should send either a Bar.Gamma or a Bar.Whatsit?
The solution you considered and discarded as hackish (putting the relation into a map) seems to give you much more flexibility, and avoids your circular reference. It also keeps the responsibility partitioned: the message types themselves shouldn't be responsible for knowing their response, should they?
You can use EnumMap, and fill it within one of the enums.
private static EnumMap<Foo, LinkedList<Bar>> enumAMap;
public static void main(String[] args) throws Exception {
enumAMap = new EnumMap<Foo, LinkedList<Bar>>(Foo.class);
System.out.println(Bar.values().length); // initialize enums, prevents NPE
for (Foo a : Foo.values()) {
for (Bar b : enumAMap.get(a)) {
System.out.println(a + " -> " + b);
}
}
}
public enum Foo {
Foo1(1),
Foo2(2);
private int num;
private Foo(int num) {
this.num = num;
}
public int getNum() {
return num;
}
}
public enum Bar {
Bar1(1, Foo.Foo1),
Bar2(2, Foo.Foo1),
Bar3(3, Foo.Foo2),
Bar4(4, Foo.Foo2);
private int num;
private Foo foo;
private Bar(int num, Foo foo) {
this.num = num;
this.foo = foo;
if (!enumAMap.containsKey(foo)) {
enumAMap.put(foo, new LinkedList<Bar>());
}
enumAMap.get(foo).addLast(this);
}
public int getNum() {
return num;
}
public Foo getFoo() {
return foo;
}
}
Output:
4
Foo1 -> Bar1
Foo1 -> Bar2
Foo2 -> Bar3
Foo2 -> Bar4
Here is an updated version of #falsarella's answer. This uses Java 8 Lambdas and java.util.function, however the principal is the same. It's just a little more succinct with the newer syntax:
import java.util.function.Supplier;
public class EnumTest {
public enum Foo {
A(() -> Bar.Alpha), B(() -> Bar.Beta), C(() -> Bar.Delta);
private final Supplier<Bar> bar;
private Foo(Supplier<Bar> bar) {
this.bar = bar;
}
public Bar getBar() {
return bar.get();
}
}
public enum Bar {
Alpha(() -> Foo.A), Beta(() -> Foo.B), Delta(() -> Foo.C);
private final Supplier<Foo> foo;
private Bar(Supplier<Foo> foo) {
this.foo = foo;
}
public Foo getFoo() {
return foo.get();
}
}
public static void main(String[] args) {
for (Foo f : Foo.values()) {
System.out.println(f + " bar " + f.getBar());
}
for (Bar b : Bar.values()) {
System.out.println(b + " foo " + b.getFoo());
}
}
}

Output of Java program

I am a Java beginner.
Can anyone explain why is it printing output 2?
interface Foo {
int bar();
}
public class Beta {
class A implements Foo {
public int bar() {
return 1;
}
}
public int fubar(final Foo foo) {
return foo.bar();
}
public void testFoo()// 2
{
class A implements Foo {
public int bar() {
return 2;
}
}
System.out.println(fubar(new A()));
}
public static void main(String[] args) {
new Beta().testFoo();
}
}
That is because you redefined Class A here:
class A implements Foo {
public int bar() {
return 2;
}
}
System.out.println(fubar(new A()));
So when you do return foo.bar(); you return 2
Because the innermost definition of A is in the testFoo() method, and its method bar() return 2.
You may also find the answer to my question from today interesting.
When you say, System.out.println(fubar(new A()));
the class A created is the one defined inside testFoo().
There are many places in java where you can hide a broader name with a more local name. This is true of parameters vs member variables, class names etc. In your case, you are hiding Beta.A with the A you defined in the method.

Java: Anonymous inner class using a local variable

How can I get the value of userId passed to this method in my anonymous inner subclass here?
public void doStuff(String userID) {
doOtherStuff(userID, new SuccessDelegate() {
#Override
public void onSuccess() {
Log.e(TAG, "Called delegate!!!! "+ userID);
}
});
}
I get this error:
Cannot refer to a non-final variable userID inside an inner class defined in a different method
I'm pretty sure I can't assign it as final since it's a variable with an unknown value. I had heard that this syntax does preserve scope in some way, so I think there must be a syntax trick I don't quite know yet.
As everyone else here has said, local variables have to be final to be accessed by an inner class.
Here is (basically) why that is... if you write the following code (long answer, but, at the bottom, you can get the short version :-):
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
final int x;
Foo foo;
x = 42;
foo = new Foo()
{
public void bar()
{
System.out.println(x);
}
};
foo.bar();
}
}
the compiler translates it roughly like this:
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
final int x;
Foo foo;
x = 42;
class $1
implements Foo
{
public void bar()
{
System.out.println(x);
}
}
foo = new $1();
foo.bar();
}
}
and then this:
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
final int x;
Foo foo;
x = 42;
foo = new $1(x);
foo.bar();
}
private static class $1
implements Foo
{
private final int x;
$1(int val)
{
x = val;
}
public void bar()
{
System.out.println(x);
}
}
}
and finally to this:
class Main
{
public static void main(String[] args)
{
final int x;
Main$Foo foo;
x = 42;
foo = new Main$1(x);
foo.bar();
}
}
interface Main$Foo
{
void bar();
}
class Main$1
implements Main$Foo
{
private final int x;
Main$1(int val)
{
x = val;
}
public void bar()
{
System.out.println(x);
}
}
The important one is where it adds the constructor to $1. Imagine if you could do this:
class Main
{
private static interface Foo
{
void bar();
}
public static void main(String[] args)
{
int x;
Foo foo;
x = 42;
foo = new Foo()
{
public void bar()
{
System.out.println(x);
}
};
x = 1;
foo.bar();
}
}
You would expect that foo.bar() would print out 1 but it would actually print out 42. By requiring local variables to be final this confusing situation cannot arise.
Sure you can assign it as final - just put that keyword in the declaration of the parameter:
public void doStuff(final String userID) {
...
I'm not sure what you meant about it being a variable with an unknown value; all that final means is that once a value is assigned to the variable, it cannot be re-assigned. Since you're not changing the value of the userID within your method, there's no problem making it final in this case.
In Java 8, this has changed a little bit. You can now access variables that are effectively final. Relevant snippet and example from the Oracle documentation (emphasis mine):
However, starting in Java SE 8, a local class can access local
variables and parameters of the enclosing block that are final or
effectively final.
Effectively final: A non-final variable or parameter whose value is never changed after it is initialized is effectively final.
For example, suppose that the variable numberLength is not declared final, and you
add the highlighted assignment statement in the PhoneNumber
constructor:
PhoneNumber(String phoneNumber) {
numberLength = 7; // From Kobit: this would be the highlighted line
String currentNumber = phoneNumber.replaceAll(
regularExpression, "");
if (currentNumber.length() == numberLength)
formattedPhoneNumber = currentNumber;
else
formattedPhoneNumber = null;
}
Because of this assignment statement, the variable numberLength is not
effectively final anymore. As a result, the Java compiler generates an
error message similar to "local variables referenced from an inner
class must be final or effectively final" where the inner class
PhoneNumber tries to access the numberLength variable:
if (currentNumber.length() == numberLength)
Starting in Java SE 8, if you declare the local class in a method, it
can access the method's parameters. For example, you can define the
following method in the PhoneNumber local class:
public void printOriginalNumbers() {
System.out.println("Original numbers are " + phoneNumber1 +
" and " + phoneNumber2);
}
The method printOriginalNumbers accesses the parameters
phoneNumber1 and phoneNumber2 of the method validatePhoneNumber
What's the problem with making it final as in
public void doStuff (final String userID)
declare the method
public void doStuff(final String userID)
The value needs to be final so that the compiler can be sure it doesn't change. This means the compiler can bind the value to the inner class at any time, without worrying about updates.
The value isn't changing in your code so this is a safe change.

Java Enums: Two enum types, each containing references to each other?

Is there a way to get around the class-loading issues caused by having two enums that reference each other?
I have two sets of enumerations, Foo and Bar, defined like so:
public class EnumTest {
public enum Foo {
A(Bar.Alpha),
B(Bar.Delta),
C(Bar.Alpha);
private Foo(Bar b) {
this.b = b;
}
public final Bar b;
}
public enum Bar {
Alpha(Foo.A),
Beta(Foo.C),
Delta(Foo.C);
private Bar(Foo f) {
this.f = f;
}
public final Foo f;
}
public static void main (String[] args) {
for (Foo f: Foo.values()) {
System.out.println(f + " bar " + f.b);
}
for (Bar b: Bar.values()) {
System.out.println(b + " foo " + b.f);
}
}
}
The above code produces as output:
A bar Alpha
B bar Delta
C bar Alpha
Alpha foo null
Beta foo null
Delta foo null
I understand why it happens - the JVM starts classloading Foo; it sees the Bar.Alpha in Foo.A's constructor, so it starts classloading Bar. It sees the Foo.A reference in the call to Bar.Alpha's constructor, but (since we're still in Foo.A's constructor) Foo.A is null at this point, so Bar.Alpha's constructor gets passed a null. If I reverse the two for loops (or otherwise reference Bar before Foo), the output changes so that Bar's values are all correct, but Foo's values are not.
Is there any way to get around this? I know I can create a static Map and a static Map in a 3rd class, but that feels fairly hackish to me. I could also make Foo.getBar() and Bar.getFoo() methods that refer to the external map, so it wouldn't even change my interface (the actual classes I have use inspectors instead of public fields), but it still feels kind of unclean to me.
(The reason I'm doing this in my actual system: Foo and Bar represent types of messages that 2 apps send to each other; the Foo.b and Bar.f fields represent the expected response type for a given message - so in my sample code, when app_1 receives a Foo.A, it needs to reply with a Bar.Alpha and vice-versa.)
Thanks in advance!
One of the best ways would be using the enum polymorphism technique:
public class EnumTest {
public enum Foo {
A {
#Override
public Bar getBar() {
return Bar.Alpha;
}
},
B {
#Override
public Bar getBar() {
return Bar.Delta;
}
},
C {
#Override
public Bar getBar() {
return Bar.Alpha;
}
},
;
public abstract Bar getBar();
}
public enum Bar {
Alpha {
#Override
public Foo getFoo() {
return Foo.A;
}
},
Beta {
#Override
public Foo getFoo() {
return Foo.C;
}
},
Delta {
#Override
public Foo getFoo() {
return Foo.C;
}
},
;
public abstract Foo getFoo();
}
public static void main(String[] args) {
for (Foo f : Foo.values()) {
System.out.println(f + " bar " + f.getBar());
}
for (Bar b : Bar.values()) {
System.out.println(b + " foo " + b.getFoo());
}
}
}
The above code produces the output you want:
A bar Alpha
B bar Delta
C bar Alpha
Alpha foo A
Beta foo C
Delta foo C
See also:
Overridding method of a specific enum
The issue isn't so much "two enums reference each other", it's more "two enums reference each other in their constructors". This circular reference is the tricky part.
How about using Foo.setResponse(Bar b) and Bar.setResponse(Foo f) methods? Instead of setting a Foo's Bar in the Foo constructor (and similarly a Bar's Foo in the Bar constructor), you do the initialization using a method? E.g.:
Foo:
public enum Foo {
A, B, C;
private void setResponse(Bar b) {
this.b = b;
}
private Bar b;
public Bar getB() {
return b;
}
static {
A.setResponse(Bar.Alpha);
B.setResponse(Bar.Delta);
C.setResponse(Bar.Alpha);
}
}
Bar:
public enum Bar {
Alpha, Beta, Delta;
private void setResponse(Foo f) {
this.f = f;
}
private Foo f;
public Foo getF() {
return f;
}
static {
Alpha.setResponse(Foo.A);
Beta.setResponse(Foo.C);
Delta.setResponse(Foo.C);
}
}
Also, you mention that Foo and Bar are two types of messages. Would it be possible to combine them into a single type? From what I can see, their behavior here is the same. This doesn't fix the circular logic, but it might give you some other insight into your design...
Since it seems you're going to be hard-coding anyways, why not have something like
public static Bar responseBar(Foo f) {
switch(f) {
case A: return Bar.Alpha;
// ... etc
}
}
for each enum? It looks like you have some overlapping responses in your example, so you could even take advantage of cases falling through.
EDIT:
I like Tom's suggestion of the EnumMap; I think performance is probably faster on the EnumMap, but the sort of elegant construction described in Effective Java doesn't seem to be afforded by this particular problem - however, the switch solution offered above would be a good way to construct two static EnumMaps, then the response could be something like:
public static Bar response(Foo f) { return FooToBar.get(f); }
public static Foo response(Bar b) { return BarToFoo.get(b); }
Interesting design. I see your need, but what are you going to do when the requirements shift slightly, so that in response to Foo.Epsilon, app_1 should send either a Bar.Gamma or a Bar.Whatsit?
The solution you considered and discarded as hackish (putting the relation into a map) seems to give you much more flexibility, and avoids your circular reference. It also keeps the responsibility partitioned: the message types themselves shouldn't be responsible for knowing their response, should they?
You can use EnumMap, and fill it within one of the enums.
private static EnumMap<Foo, LinkedList<Bar>> enumAMap;
public static void main(String[] args) throws Exception {
enumAMap = new EnumMap<Foo, LinkedList<Bar>>(Foo.class);
System.out.println(Bar.values().length); // initialize enums, prevents NPE
for (Foo a : Foo.values()) {
for (Bar b : enumAMap.get(a)) {
System.out.println(a + " -> " + b);
}
}
}
public enum Foo {
Foo1(1),
Foo2(2);
private int num;
private Foo(int num) {
this.num = num;
}
public int getNum() {
return num;
}
}
public enum Bar {
Bar1(1, Foo.Foo1),
Bar2(2, Foo.Foo1),
Bar3(3, Foo.Foo2),
Bar4(4, Foo.Foo2);
private int num;
private Foo foo;
private Bar(int num, Foo foo) {
this.num = num;
this.foo = foo;
if (!enumAMap.containsKey(foo)) {
enumAMap.put(foo, new LinkedList<Bar>());
}
enumAMap.get(foo).addLast(this);
}
public int getNum() {
return num;
}
public Foo getFoo() {
return foo;
}
}
Output:
4
Foo1 -> Bar1
Foo1 -> Bar2
Foo2 -> Bar3
Foo2 -> Bar4
Here is an updated version of #falsarella's answer. This uses Java 8 Lambdas and java.util.function, however the principal is the same. It's just a little more succinct with the newer syntax:
import java.util.function.Supplier;
public class EnumTest {
public enum Foo {
A(() -> Bar.Alpha), B(() -> Bar.Beta), C(() -> Bar.Delta);
private final Supplier<Bar> bar;
private Foo(Supplier<Bar> bar) {
this.bar = bar;
}
public Bar getBar() {
return bar.get();
}
}
public enum Bar {
Alpha(() -> Foo.A), Beta(() -> Foo.B), Delta(() -> Foo.C);
private final Supplier<Foo> foo;
private Bar(Supplier<Foo> foo) {
this.foo = foo;
}
public Foo getFoo() {
return foo.get();
}
}
public static void main(String[] args) {
for (Foo f : Foo.values()) {
System.out.println(f + " bar " + f.getBar());
}
for (Bar b : Bar.values()) {
System.out.println(b + " foo " + b.getFoo());
}
}
}

Categories

Resources