I think this should be really common, but I canโt find the best practices. Suppose I have the following class:
public class Equation { private Operator operator; private Object leftValue; private Object rightValue;
This class has been with us for several years and is well used. Now I need to make serializable. How to do it?
Just add implements Serializable
In this case, the Equation
class only works as long as the values โโare Serializable
. Since the equations really only work on numbers (maybe dates and strings?) That can work. But the values โโcan be any Object
, so there should be a better way.
Make Serializable
Values
public class Equation implements Serializable{ private Operator operator; private Serializable leftValue; private Serializable rightValue;
This works anyway, but these changes are an API transition. And no matter what I do, I need to modify all the code with the class, which will lead to a potentially even greater gap in the API. For a large software system that can take age.
Set Serializable
values, leave getters and setters as they are
public void setLeftValue(Object leftValue) { if (!(leftValue instanceof Serializable)) throw new IllegalArgumentException("Value must be Serializable!"); this.leftValue = leftValue; }
This code does not destroy the existing API, but changes the behavior of the code. But if I assume that all the values โโare Serializable
anyway, I feel that this might be the way to go. I can even put new setters next to the old ones and condemn them so that future developers understand which objects to use.
Make transient
values:
At least what Sonar offers. However, this leads to an unusable class, at least in all cases where we really need Equation
be Serializable
.
Create an implementation of Serializable
:
public class SerializableEquation extends Equation implements Serializable{ private Serializable leftValue; private Serializable rightValue;
So we have to use a whole class for serialization purposes, which seems ugly, right?
Question:
What is a good way to handle this use case? I ideally do not want to violate the API. And, seeing that Java has not yet broken the API, there must be a way to deal with such cases.