Solution to 0378: Comparing people
See code at solutions/code/tutorialquestions/question0378
For the Person
class, have a look at the model solution code. Do you understand the significance of @Override
on the toString
method?
The PersonComparator
interface is simple: see the sample code.
The three concrete comparators, SurnameComparator
, ForenameComparator
and TelephoneNumberComparator
are very similar: they simply compare the relevant String
field. I did this using the compareTo
method provided by the String
class; you might have implemented a dictionary-based comparison directly. This is fine and educational, but in practical software development it is better to reuse an existing implementation if possible.
For the findMin
method see the sample solution. There's not much difficult about this; the key thing is that this method is polymorphic: it is a single method that works for any type of PersonComparator
.
Inspect the sample code for the TwoTieredComparator
. It should make reference only to the PersonComparator
interface. The Demo
code shows how this two-tiered comparator can be used, and how you can nest two-tiered comparators to build a three-tiered comparator.
The advantages of the compositional approach are:
- A smaller number of classes, meaning less code to maintain
- The possibility to combine comparators in arbitrary ways, not being restricted to the ways that were predicted at design time
- The possibility of being able to modify comparators at runtime by re-configuring them (this would be possible if a two-tiered comparator supported resetting the
first
andsecond
fields) - It is possible to write additional comparators and compose them with existing comparators
The disadvantages are:
- It might be that certain combinations of comparators would be undesirable. With the compositional approach, arbitrary combinations are possible, including any that would be undesirable. For instance, it would be very unusual in practice to compare people based on their first name, then telephone number, then surname. With the compositional approach, this arrangement could be created by accident.
- It could be slightly more efficient to use a predefined multi-tiered comparator, as the compiler might be able to do a good job of optimising the class, given the complete picture of what the class should do. Fewer optimisations are possible with the compositional approach. However, I regard this as a negligible benefit, unless comparing people would be the bottleneck of an application.