Dear all, As we know that value object is used to wrapping the state of a record. We always use in enterprise application. I want to know what is the best approach between these options...
The difference between those are: - Option 1, each attributes is initialized at the point its is declared. So when a client initializes Person (using constractor no-args or with args), the instance of Person have had all default values of attributes already.
- Option 2, when a client initialize Person using constractor no-args, all attributes will have the value after that client set every attributes one by one (using setter method).
I think that option 2 is better than option 1 because we only initialize the attributes at the time we need and leave the rest attributes with null value.
Could you share your opinions about this, please? Correct me if I am wrong...
Both approaches are correct. It is a question of trade-off. If you follow 'Object creation is initialization', then you should use Option 1. This is most effective if Java supports the concept of a destructor, which it does not (finalize does not count, as there is no guarantee that it will be called).
The advantage in option 1 is that you can ensure that the created object will contain some value (you can always throw exceptions in the constructor if null values or bad values are passed, thereby not creating the instance). This guarantee is not possible in option 2.
On the other hand, option 2 is more flexible. You can add many parameters. If some parameters are optional, this is easily taken care of also. Typically, you should have some sort of an isValid():boolean method in option 2, which a caller can use to check if the object is in a valid state.
For simple VOs, I would go with option 1. For complex VOs or VOs with a lot of parameters, I would go with option 2 with an isValid() method.