Suppose that i have a List<Person> all
data structure, where Person
is defined as:
class Person {
String firstName;
String secondName;
boolean hasValidDrivingLicense;
}
I want to mantain a redundant List<Person> drivers
that contains only the persons that have a valid driving license. I think it can also be seen as an index (well an index would contain all the items, but the purpose is very similar).
This is to avoid the need for looping through the entire list each time i need those data.
(Looping each time has the advantage that i have a single-authoritative-representation of my hasValidDrivingLicense information; abandoning this road requires: a)valid reasons b)tested alternative. The reasons depend on the specific problem; the alternative is what i'm developing here :-) )
the problem
I probably have something like this:
void add(Person p) {
all.add(p);
if (p.hasValidDrivingLicense()) {
drivers.add(p);
}
}
this often works.
Person p = new Person(); //then set fields, of course.
add(p);
p.setHasValidDrivingLicense(true);
Here it doesn't. So the problem is: redundant information may misalign. Indexes may "broke".
solutions
- Person's hasValidDrivingLicense property implement Observable design pattern (or publish-subscriber, what in swing is based on the Listener interface) If objects can change and i want my indexes to be up-to-date with their changes, i need a way to notify the index-mantainer that an object has changed a relevant property. Observable seems to be a definitive solution. No questions about it.
- Person is immutable
Problem
Immutability seems to be a viable solution, but, from the collection maintainer point of view, that is the person who writes the code:
public void add(Person p) {
...
}
has to ensure that p is immutable or better, that at least hasValidDrivingLicense is final.
a) this may be done through reflection (http://stackoverflow.com/questions/203475/how-do-i-identify-immutable-objects-in-java) But doesn't this require a new performance evaluation? Doesn't reflection come at a cost?
b) are there, perhaps in design patterns or in new features of the language (eg.annotations) other solutions to this problem?