From a performance perspective both approaches are comparable. Yes, method 2 will use some additional memory and require a few more instructions for instantiating your NameVO
, but unless you're dealing with millions of objects, I would not worry too much about that.
From a coding standards perspective, method 2 is superior over method 1. In general, composite values (such as names) deserve their own object.
First of all, it allows you to add additional methods in your NameVO
, such as the likely String getFullName()
, which handles the possibility of having null
as a middleName. This also gives you the flexibility to change the contents of a NameVO
later on, for example by adding initials, salutations, etc.
Secondly, it gives you the option to reuse NameVO
in other contexts. For example, you could have a Customer
object with a name
field, and a Supplier
with a name
field, etc.
Thirdly, if your code uses validation, you can decouple the validation of the contents of a name from the validation of the existence of a name.
Furthermore, by adding an equals
and hashCode
, you also gain the possibility to store your objects in a Map
, indexed by NameVO
.
As an aside, I would even go so far as to suggest a slightly modified version of your method 2:
public class SampleVO {
NameVO name;
// getters and setters
}
//Name object
public class NameVO {
final String firstName;
final String middleName;
final String lastName;
public NameVO(String firstName, String middleName, String lastName) {
// assignments
}
// getters
}
This effectively makes your NameVO
immutable, making it more suitable for use as a key in a Map
. It also makes it safer to pass NameVO
objects around without having to fear side effects.