While reading this page about the builder pattern, I noticed the class contained optional parameters.
Example:
public static class Builder {
// Required parameters
private final int servingSize;
private final int servings;
// Optional parameters - initialized to default values
private int calories = 0;
private int fat = 0;
private int carbohydrate = 0;
private int sodium = 0;
public Builder(int servingSize, int servings) {
this.servingSize = servingSize;
this.servings = servings;
}
If we remove the builder pattern, so our class looks like this:
public final class NutritionFacts
{
private final int servingSize;
private final int servings;
private final AbstractMap<String,int> optionalFacts;
public NutritionFacts (int servingSize, int servings, optionalFacts)
{
this.servingSize = servingSize;
this.servings = servings;
// code to make defensive copy of optionalFacts
}
}
Would there be any problem or downside to taking those optional parameters and placing them inside an AbstractMap and passing it to the constructor?
The only disadvantage I can see is the work to validate it.
You would have to create a defensive copy
Create a private List<String> validOptionalFacts; and loop through the keys of the AbstractMap and ensure the String values are valid and if not, throw an exception.
Check and throw an exception for duplicated parameters.
For this small example, it might be okay to have the optional parameters outside of a map, but suppose you had 10+ optional parameters, this would mean creating new setters/getters for those parameters, where as if it were a map, I can have a method like this:
public NutritionFacts updateParameter(String key, int value){
//call method to validate the key/value
//update fact
//return a new object that reflects our change
return this;
}
public int retrieveValuefor(String key){
//call method to validate the key
//Get value associated with the key
//return value associated with the key
return factValue;
}
The way I see it there are some disadvantages in addition to the fact that validation might become much more cumbersome, as you already pointed out.
As noted in the comments to your question, your approach will only work if your optional parameters all have the same value. If they do not, you will have to resort to using Map<String,Object>. That in turn will make it hard to deal with these parameters, as you lost all type information.
Secondly, and I think this is the main issue with your approach: When utilizing a method such as updateParameter(String key, int value) the knowledge about which parameters the object being built requires is transferred from the builder to the client using this builder. Compare:
new Builder.updateParameter("calories", 0)
.updateParameters("fat", 1)
.updateParameters("carbohydrates",0)
.build();
new Builder.calories(0)
.fat(1)
.carbohydrates(0)
.build();
With the second approach the client will know that it is possible to set carbohydrates, because the builder provides a public method for it. It will not be possible to set the parameter mumbojumbo, because no such method exists.
In the first approach, will the client know if there is an additional parameter proteins? What happens if you mistype? What happens if a provided parameter is not actually used by the object being built? All these questions don't even pose themselves when sticking to the approach without the map.
In summary: Your approach provides seemingly more convenience (at first glance) at the cost of safety, readability and maintainability.
The map approach is bad for a few reasons:
Your approach is against regular OO programming paradigms.
When you define an object you also define all of the possible attributes that can be assigned to it, the code that uses the object does not define characteristics of the object, it simply uses the object for its intended purpose.
The code requires knowledge of the object by any code that uses the object.
The code is less readable, more prone to errors, and difficult to be used in more than exactly one place.
The code creates the possibility of throwing a Runtime Exception where none existed before (this alone is a reason to avoid your approach).
If I would like to use an object made by another developer I simply create an instance of that object (or perhaps I am altering code that has already created an instance of the object) and look at all the valid attributes I can set and get.
Under this map scenario am I supposed to look back since the instantiation of the object and find every alteration of the map? What if I want to add a new parameter to the map, how do I know if it is a valid parameter? How will code down the line know what mystery parameters are contained in this map?
If your solution to this problem is to define the valid map parameters inside the object, what is the point of doing this as opposed to the standard way of defining objects?
There are many more reasons why this approach would be less than desirable, but what exactly is the solution this solving? Creating fewer getters and setters? Any IDE will generate them automatically, but even if that were not the case a very slight improvement in coding time would never be worth the laundry list of problems this solution would create.
Related
So, in the famous Effective Java book, it introduces a Builder pattern where you can have an inner static Builder class to instantiate a class. The book suggests the following design of a class:
public class Example {
private int a;
private int b;
public static class Builder() {
private int a;
private int b;
public Builder a(int a) {
this.a = a;
return this;
}
public Builder b(int b) {
this.b = b;
return this;
}
public Example build() {
return new Example(this);
}
}
private Example(Builder builder) {
this.a = builder.a;
this.b = builder.b;
}
}
However I have failed to understand why do we really need an inner Builder class? The above code have duplicate lines for field declarations (int a, b), this would become relatively messy if we had more fields.
Why not just get rid of the Builder class, and let Example class take on all the set methods that were in Builder class?
So to instantiate Example, it would become Example e = new Example().a(3).b.(3); instead of Example e = new Example.Builder.a(3).b(3).build();
NOTE: The book suggests this pattern for classes that have a long list of parameters to be set.
Builder is a pattern for the construction of complex objects. I wouldn't count your example as complex; indeed, the builder adds an awful lot of unnecessary code, rather than just using constructor parameters.
There are a few reasons why you'd want to use a builder:
To construct complex immutable objects. Immutable objects need to have final (or logically final) fields, so they must be set at construction time.
Let's say that you have N fields, but you only want to explicitly set some of them in certain use cases. You would need up to 2^N constructors to cover all of the cases - known as "telescoping", since the length of the parameter list gets longer and longer. The builder allows you to model optional parameters: if you don't want to set that parameter, don't call that setter method.
To allow self-documentation of the parameters' meaning. By naming the setter methods appropriately, you can see what the values mean at a glance.
It also helps to verify that you are not accidentally reversing parameters of the same type, since you can see what each value is used for.
If the fields in the outer class are final, then the builder is necessary if you want to incrementally specify parameter values, as all fields must be initialized in the constructor.
The builder inner class allows fields to be initialized incrementally.
As others have pointed out, this applies to immutable objects as well. The fields don't need to be final; they effectively will be if no setters are supplied in the outer class.
The builder can possibly accumulate the parameters more efficiently than direct construction. Consider the StringBuilder. It allocates a temporary buffer to accumulate partial results. The "build" operation in its case is toString().
Finally, there could be things you just can't do in the constructor of a class. If you need to pass a value to a super constructor, but that value is not part of the arguments to your constructor, it may not be possible to, since you must call super() first, and you might not be able to create the argument(s) as a simple expression inside the super(...) call. The BoxLayout comes to mind. You pass the JPanel to the BoxLayout constructor. You pass the layout to the JPanel constructor. Chicken and egg. And this code is not allowed, because this is not yet constructed.
class X extends JPanel {
X() {
super( new BoxLayout(this) ); // Error: Cannot use "this" yet
}
}
Fortunately, a JPanel is not immutable; you can set the layout after construction.
The rationale is for complicated classes. Notice that the Builder object returns itself, so one can do chaining, such as:
Example exp = Example.Builder().a(5).b(10).build();
Apache uses this approach in some cases to allow the incremental setting of various values. It also allows the .build() method to do some checking of all of the correct values to make an object if desired.
Say I have some class:
public class A {
private int val = 0;
public int getVal() {
return val;
}
public void addFrom(A otherA) {
this.val += otherA.val;
if (otherA.val > 0)
otherA.val = 0;
else
otherA = Math.abs(otherA.val);
}
}
Should I be using getter methods instead to use otherA's val variable? Is it better style to do so?
Edit: This is a very simplified version of a class that takes much too long to read. But assume that there IS lazy initialization going on, that there are other methods that access this class, etc. I have updated the example method so that this may be more clear, but I hope it is clear that my question involves accessing the other object's variables, and want to know if it is faux pas to use a direct variable access for something that is not "this".
No, absolutely not.
You should use the variable directly when you're inside the class' members, and use getters in every other situation (when you would get an error because val is private anyway).
public int getVal() is intended to present your gift(variable) within a box to the outside world (encapsulation). Do you give gifts yourself in a box? It's weird, so use the variable as it is.
You can use variables, but the current code does not compile. Probably, the return should be int instead of boolean.
Probably, your intention is to override the compareTo method from the Comparable interface
Adding an unnecessary getter reveals internal structure and this is an opportunity for increased coupling.
A truly well-encapsulated class has no setters and preferably no getters either. Rather than asking a class for some data and then compute something with it, the class should be responsible to compute something with its data and then return the result.
Use of accessors to restrict direct access to field variable is preferred over the use of public fields, however, making getters and setter for each and every field is overkill. It also depends on the situation though, sometimes you just want a dumb data object. Accessors should be added for field where they're really required. A class should expose larger behavior which happens to use its state, rather than a repository of state to be manipulated by other classes.
I realize this probably cannot be answered, but I'm looking for whether there is some sort of guidance about whether to use private members directly or public accessors inside class methods.
For example, consider the following code (in Java, but it would look very similar in C++):
public class Matrix {
// Private Members
private int[][] e;
private int numRows;
private int numCols;
// Accessors
public int rows(){ return this.numRows; }
public int cols(){ return this.numCols; }
// Class Methods
// ...
public void printDimensions()
{
// [A] Using private members
System.out.format("Matrix[%d*%d]\n", this.numRows, this.numCols);
// [B] Using accessors
System.out.format("Matrix[%d*%d]\n", this.rows(), this.cols());
}
The printDimensions() function illustrates two ways to get the same information, [A] using private members (this.numRows, this.numCols) or [B] via accessors (this.rows(), this.cols()).
On one hand, you may prefer using the accessors since there is no way you could inadvertently change the value of the private member variables. On the other, you may prefer accessing the private members directly in hopes that it would remove the unnecessary function call.
I guess my question is, is either the de-facto standard or preferred?
It's a style call. I prefer to use accessors, because IMHO the function call overhead is small enough that in most cases it doesn't matter, and this usage preserves the data abstraction. If i later want to change the way the data is stored, i only need to change the accessors, instead of hunting for all the places where i touched the variables.
I don't feel strongly about it, though, and i would break this "rule" if i thought i had a good reason to.
IMHO, accessors are more a matter of structure and data management rather than accessors per se. Sometimes, you need to preprocess some data before returning it. Think about this example:
public class Foo {
private List<Bar> bars = null;
//Methods and stuff
public List<Bar> getBars() {
if(bars == null)
bars = SomeClass.loadBars();
// You can also use
// setBars(SomeClass.loadBars());
return bars;
}
}
In this case, your getter is not only wrapping your field, but returning an initialized field whenever you invoke it. Using the accessors inside a class gives the same benefits that for outsiders, you abstract yourself from the particular details of a field and you can obtain it after processing it.
On the other hand, if your field is returned directly (say, a String) it doesn't matter if you use a get or you don't, but you might want to use a get to respect a standard in your code.
In the end, it all boils down to coding style.
I have other objects, including subclasses of the object, use the accessors, but have the object itself use the fields. That way there is a clear distinction between the internals and the interface with the rest of the world. Hiding the contents of the class from itself seems unnecessary and potentially confusing. If something really benefits from having its implementation hidden from other parts of the object then break it out into a separate object.
Despite Java tutorials, Wikipedia searches, stackoverflow trolling, and hours of reading code samples, constructors still confuse the crap out of me. I've got three related questions that I've been trying to answer to help ME understand constructors a little better.
First, I've been under the impression that constructors need to be named the same as their classes. Consider:
public class Money {
public Money(long l) {
this.value = l;
}
public Money(String s) {
this.value = toLong(s);
}
public long getLong() {
return this.value;
}
public String getString() {
return toString(this.value);
}
}
I see this as four constructors...correct? So it appears that constructors not named the same as the class which contains them allowable. Can someone confirm that?
Second, I seem to have a block against understanding the set and get methods. Consider:
public class GetSetSample {
public int getFoo() {
return int Foo;
}
public void setFoo(int fooValue) {
int Foo = fooValue;
}
}
Why can't I just do this:
public class getFoo(int fooValue){
foo=fooValue;
}
and use foo = getFoo(12) from some other class/method?
The third question is a little more esoteric, but will help me conceive of the bigger picture...which is my learning style, and conducive to my ability to trace program flow when debugging. The get and set methods suggest a "to" and "from" relationship to me. e.g., Passing a value "to" a constructor, receiving the result "from" the get method. It seems to me though that the "to" and "from" will change depending on your perspective. I think that any setMethod is setting parameters for an object, even though the variable comes FROM another class or method, and the GetMethod is getting the resulting object (say, this.foo) with the appropriately set parameter. No matter where the get or set is used, in a main method or a standalone class with a single constructor, 'set' is always associated with sending a parameter and get is always associated with receiving an object with that parameter. Is that a good understanding? or am I missing a vital part?
Question 1:
I see this as four constructors...correct?
No, that class has two constructors and two methods. (getLong and getString are the methods.)
Question 2:
Why can't I just do this:
public class getFoo(int fooValue){
foo=fooValue;
}
Well, that's trying to declare a class with parameters, and also you're setting a value in a get method, which would be extremely weird. It's not clear what you're trying to achieve here, but that code is thoroughly invalid.
Question 3:
The get and set methods suggest a "to" and "from" relationship to me.
Well it's not really a relationship IMO. A relationship suggests something longer term than either of these methods. A setter typically changes the state of an object in some way, and a getter typically just returns some aspect of the state of an object. It's not really clear what the rest of your explanation meant, because you're playing somewhat fast and loose with terminology. For example: "get is always associated with receiving an object with that parameter" doesn't really make sense to me. Objects don't have parameters, methods/constructors do - and getters can fetch primitive values or references...
I suspect you would benefit from reading the "Classes" part of the Java tutorial, which talks about constructors and methods.
Regarding the first answer, there's only 2 constructors. The difference is on how they are going to be called (called using a string will use the construction having a string has a parameter and called using a long will use the other one). So to answer, yes a constructor has the same name as the class.
The two constructors :
public Money(long l) {
this.value = l;
}
public Money(String s) {
this.value = toLong(s);
}
Regarding the second answer, getters ans setters are not meant to be classes. They are supposed to be within the class itself.
Consider this example which uses getter and setters to get ans set value for the printer class :
public class Printer {
#Inject #Informal Greeting greeting;
private String name;
private String salutation;
public void createSalutation() {
this.salutation = greeting.greet(name);
}
public String getSalutation() {
return salutation;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
A good read of this link could definitly help you out !
Java oriented-object principles
You've shown 2 constructors, which do need to have the same name as the class.
You've also shown two "getter" methods, which return the value of the class variable in the form requested by the user. You can also create "setter" methods, which are used to transfer values into class variables.
You use a constructor to create an object of a particular class, and optionally to set some or all of its internal state (that is, its member variables).
You use setters and getters to isolate the class variables from the outside world, so you don't need to allow other code to access them directly. Why? Because, before a setter updates a variable, it can verify that the new value is valid, and that the operation doesn't violate any or the rules (the "business logic") that are required for the class to work properly.
So you could add a setter and update the constructor to use it:
public Money(long l) {
setValue(l);
}
public Money(String s) {
setValue(toLong(s));
}
// Example setter that validates `l` by prohibiting negative values
public Money setValue(long l) {
if (l < 0) {
// Warn about negative values
}
this.value = l;
return this; // Return the current object to allow chaining; see below.
}
Note that a setter usually doesn't need to return a value (that is, it can be type void), but it's often helpful to return the object itself. That allows you to write code like this:
Money earnings = new Money().setValue(4).setOtherField("foo");
This creates an object of type Money, sets various attributes, and stores it in the variable earnings. Clearly, this isn't terribly useful for a simple class like this, but it can be very helpful for more complex classes:
Paycheck check = new Paycheck("MyCompany")
.setEmployee("YourName")
.setSalary(50,000)
.setPaySchedule(Schedule.BIWEEKLY)
.setAccountNumber("1234567")
.setDefaultTaxRate();
I would like to try to answer your implied conceptual questions -- you've already got plenty of examples of this and that, so I'm just going to try to explain. I have no doubt you have heard most of this -- maybe all of this -- before, but am not sure and not sure which parts.
Object-oriented programming centers mostly around objects; an object is an amalgamation of code and data. You define objects by writing a class, and you create one or more copies of the object defined by that class with the class constructor (called instantiating the class).
A parallel in other languages: you can have a data structure of related items and a set of subroutines that operate on that data structure. Think of a class as a way of collecting the items in that data structure and the subroutines that operate on it into one unit.
After you have invoked a constructor, you have a copy of the data defined in that class and a way to refer to that copy. By referring to that instance when you invoke a class method, you operate on that copy of the data with the methods defined in that class.
If you were to do this in a non-OO language, you could have a routine that created a copy of the data structure in memory and then only use the methods prescribed for it on that data structure. You could have a pointer to the copy in memory and pass that pointer as a parameter to every subroutine that operated on it, and in fact that's the way some pre-OO systems were programmed.
A constructor is similar to a method call that returns a value; it involves (or can involve) the execution of statements, and it always returns an object of that class. There are also differences between a constructor and a method; until the constructor completes, for instance, the object is not fully created and shouldn't have some methods invoked on it.
So I hope that helped; if there are conceptual things you still have questions about, perhaps something in here will help you form a specific question so we can explain things further.
Many people have found that if they have spent years learning languages such as COBOL and FORTRAN then changing to OO programming involves unlearning the old languages. I certainly found this when I first tackled C++ 20 years ago. From your description you are clearly struggling with the concepts and I sympathize.
I don't think there is a simple recipe. Practice at the simple examples and don't be disheartened. Don't be afraid to ask on SO - if the questions are clearly asked you will get a useful answer.
Get a good IDE (Eclipse, Netbeans, etc.) which allows you to "look inside" objects with the debugger. Hopefully at some stage things will click!
Question 1 - Basic Java Classes:
There's pretty much only 3 things you're going to find in a Java class
Field/attribute (Depending on your language of origin)
Method
Constructor (Which looks like a special kind of method)
Every class is going to have a class name that shares the name of the file it's located in. So to expand Money out a bit:
Money.java
----------
public class Money {
// This is a field/attribute
Long value;
// This is a constructor
public Money() {
this.value = Long(0L);
}
// This is a method
public Long getValue() {
return value;
}
// Another method
public void makeMoney(Long moreMoney) {
this.value = this.value + moreMoney;
}
} // Everything in here is part of the Money class
The only distinction between a constructor and a method is that a constructor has no specified return value, which is declared as a type right before the name of a potential method. Constructors do have to be named the same as the class they are contained in, but why is implied in how they are written.
Another way of looking at it is if you remove all of the non-type related Java keywords (public, private etc., but not things like float and int) from the front of the method you're looking at (A list of which you can find here), is there anything left in front of the method?
With the Money we have at the moment, it would look like this:
Money()
Long getValue()
void makeMoney()
The constructor is the one that has no type for the return value, because it is implied in the declaration.
Question 2/3 - Get/Set methods:
I'm going to say something potentially controversial, but don't worry about these yet. Get/Set are essentially patterns for Object Oriented development, and generally good Java style, but they aren't required (Last I checked, Android development actually discourages their use when possible for optimization reasons). Moreover, not all fields in your objects will be accessible or mutable so writing them isn't mandatory.
If you declare all of your fields as public (Like the 'value' field is implied to be right now), you simple can do this:
Money myMoney = new Money(new Long(40L));
System.out.println(myMoney.value) // 40
myMoney.value = new Long(20L);
System.out.println(myMoney.value) // 20
Aside from that, the notion of get() and set() are just methods. There is nothing special about them at all. The main reason they exist is because for general Object-Oriented programming, you shouldn't have to directly modify the internal workings of an object (This is the principle of Encapsulation). Everything you should need to affect state or get something out of it should be handled by a method.
In a pithy one-liner: If you need to know the fields of an object to use it, you designed it incorrectly.
Big Picture
So what get() and set() really are is a pair of commonly written methods that happen to affect a field in an object in an extremely simple way (get() is a simple access to a field, set() is assignment to that field). It's just that other methods you write will happen to do more complicated stuff than that.
[Mind the gap: I know that the best solution would be to get rid of the enum completely, but that's not an option for today as mentioned in the comments, but it is planned for the (far) future.]
We have two deployment units: frontend and backend. The frontend uses an enum and calls an EJB service at the backend with the enum as a parameter. But the enum changes frequently, so we don't want the backend to know its values.
String constants
A possible solution would be to use String constants insteadof enums, but that would cause a lot of little changes at the frontend. I'm searching a solution, which causes as few changes as possible in the frontend.
Wrapper class
Another solution is the usage of a wrapper class with the same interface as an enum. The enum becomes an wrapper class and the enum values become constants within that wrapper. I had to write some deserialization code to ensure object identity (as enums do), but I don't know if it is a correct solution. What if different classloaders are used?
The wrapper class will implement a Java interface, which will replace the enum in the backend. But will the deserialiaztion code execute in the backend even so?
Example for a wrapper class:
public class Locomotion implements Serializable {
private static final long serialVersionUID = -6359307469030924650L;
public static final List<Locomotion> list = new ArrayList<Locomotion>();
public static final Locomotion CAR = createValue(4654L);
public static final Locomotion CYCLE = createValue(34235656L);
public static final Locomotion FEET = createValue(87687L);
public static final Locomotion createValue(long type) {
Locomotion enumValue = new Locomotion(type);
list.add(enumValue);
return enumValue;
}
private final long ppId;
private Locomotion(long type) {
this.ppId = type;
}
private Object readResolve() throws ObjectStreamException {
for (Locomotion enumValue : list) {
if (this.equals(enumValue)) {
return enumValue;
}
}
throw new InvalidObjectException("Unknown enum value '" + ppId + "'");
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (ppId ^ (ppId >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof Locomotion)) {
return false;
}
Locomotion other = (Locomotion) obj;
if (ppId != other.ppId) {
return false;
}
return true;
}
}
Did you already had the same problem? How did you solved it?
Ok, let me see if I understand. You said that
"The frontend uses an enum and calls
an EJB service at the backend with the
enum as a parameter. But the enum
changes frequently, so we don't want
the backend to know its values"
When you say "values" I assume you are referring to the numeric value you pass in the enum constructor and not to the enum constants themselves.
Therefore, this implies that the frontend and the backend will have two different versions of the enum class, but the enum constants in them will be the same.
I am only assuming the communication is via RMI (but this is not entirely clear in your post).
Now, serialization/deserialization of enums works different than with other objects. According to the Java Serialization Specification, when a enum is serialized, only its name is serialized. And when it is deserialized, it is built using the Enum.valueOf(name) method.
So, your original wrapper proposal would not work, because the server, due to stipulated serialization of Enums will never know the actual value of the enums in the client.
Bottom line, if you intend to pass an enum to the server there is no possible way to do what you pretend to do because the values in the frontend will never reach the backend if serialization is implied.
If RMI is implied, a good solution would be to use code mobility, this way you could place the problematic class in a repository accessible to both, server and client, and when the frontend developers change the class definition, you can publish the class in the repository and the server can get it from there.
See this article about dynamic code downloading using code base property in RMI
http://download.oracle.com/javase/6/docs/technotes/guides/rmi/codebase.html
Another possible solution is that you could stop using a Java Enum and use Java class with final constants, as we used to do in the old days before enums, and that way you can ensure that its values will be properly serialized when they are are sent to the backend.
Somewhat like this
public class Fruit implements Serializable{
private static final long serialVersionUID = 1L;
public final Fruit ORANGE = new Fruit("orange");
public final Fruit LEMON = new Fruit("lemon");
private String name;
private Fruit(String name){
this.name = name;
}
}
This way you can be in full control of what happens upon deserialization and your wrapper pattern might work this way.
This type of construction cannot substitute an enum completely, for instance, it cannot be used in switch statements. But, if this is an issue, you could use this object as the parameter sent to the server, and let the server rebuild the enum out of it with its version of the enum class.
Your enum, therefore, could have two new methods, one to build Java instances out of the enum itself:
public static Fruit toFruit(FruitEnum enum);
public FruitEnum valueOf(Fruit fruit);
And you can use those to convert back and forth versions of the parameter for the server.
It's an odd request, as i would think the server should know about the values of what is going into the database, but ok, i'll play along. Perhaps you could do this
public enum Giant {Fee, Fi, Fo, Fum};
public void client() {
Giant giant = Giant.Fee;
server(giant);
}
public void server(Enum e) {
String valueForDB = e.name();
//or perhaps
String valueForDB = e.toString();
}
For data transfer between frontend and backend both need to use the same class versions because of possible serialization during marshalling parameters. So again they have to know exactly the same enums or whatever other classes you try to use. Switching enums to something different won't work either. You have to set on a known class identiy for both.
So if the server should do actions based on some kind of processing/calculating the values of the parameters use strings or whatever other non-changing class you decide on and put your values inside: string of characters, array of numbers or whatever.
So if you put your database id inside the wrapper object the server will be able to get the objects out of the database. But still - they both need exact the same version of the wrapper class in their classpaths.
Okay, I can't be too exact because I don't see your code but in my experience something that changes like that should be external data, not enums.
What I almost always find is that if I externalize the information that was in the enums, then I have to externalize a few other pieces as well, but after doing it all I end up factoring away a LOT of code.
Any time you actually use the values of an enum you are almost certainly writing duplicate code. What I mean is that if you have enums like "HEARTS", "DIAMONDS"...
The ONLY way they can be used in your code is in something like a switch statement:
switch(card.suit)
case Suit.HEARTS:
load_graphic(Suit.HEARTS);
// or better yet:
Suit.HEARTS.loadGraphic();
break;
case Suit.SPADES:
Suit.SPADES.loadGraphic();
...
Now, this is obviously stupid but I made the stupid constraint to say that you USED the values in the code. My assertion is that if you don't USE the values you don't need an enum--Let's not use the values in code and see:
card.suit.loadGraphic();
Wow, all gone. But suddenly, the entire point of using an enum is gone--instead you get rid of the whole class preload a "Suit" factory with 4 instances from a text file with strings like "Heart.png" and "Spade.png".
Nearly every time I use enums I end up factoring them out like this.
I'm not saying there isn't any code that can benefit from enums--but the better that I get at factoring code and externalizing data, the less I can imagine really needing them.