Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java patterns to maintain consistent the indexes on data in a collection

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

  1. 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.
  2. 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?

like image 711
AgostinoX Avatar asked Nov 05 '22 02:11

AgostinoX


1 Answers

I guess what you want is a "live" filtered view of your all collection.

This can be done quite nicely with Google Guava and a Predicate:

http://docs.guava-libraries.googlecode.com/git-history/v11.0.2/javadoc/com/google/common/collect/Collections2.html#filter%28java.util.Collection,%20com.google.common.base.Predicate%29

On the other hand, just implementing a List personsWithDriversLicens() {...} is also easy, so perhaps Guava is overkill - depends on your needs, including performance characteristics.

like image 135
dpnmn Avatar answered Nov 09 '22 11:11

dpnmn