Skip to content
plrigaux edited this page May 19, 2016 · 17 revisions

Purpose

This is a library that provide different useful comparators for your common projects.

History

This project started with the idea do create a version of a "Natural Comparator" that can be configured according to different needs or contexts. During the development other types of comparators came up and I decided to implemented them as well.

Comparators

For now, here the implemented comparators.

  • [Natural Order Comparator](Natural Order Comparator): A configurable comparator that sort strings with numerical component in the natural order.

  • [Insensitive Comparator](Insensitive Comparator): Comparators that handle different insensitive strategies.

  • [Other Comparators](Other Comparators): Other trivial comparators.

#Philosophy

The philosophy behind this library is the following.

Immutability

In Effective Java, Joshua Bloch makes this compelling recommendation :

"Classes should be immutable unless there's a very good reason to make them mutable....If a class cannot be made immutable, limit its mutability as much as possible."

The created comparators are immutable, in other word unchangeable. The advantages are:

  • Simple to construct, test, and use.
  • Automatically thread-safe and have no synchronization issues.
  • Safe for use by untrusted libraries.

Avoid string copy

For the sake of performance, the library avoid to make string copy or manipulation for comparing strings.

As your might already know, most one liner comparator rely on a string copy in the backend. For example, it's easy to make a comparator that ignore whitespaces as shown in the snippet bellow.

s1.replace("\\s", "").compareTo(s2.replace("\\s", ""))

Behind the scene the above snippet creates two Pattern objects that need to compile two time the regular expression and then create a new string for both s1 and s2. We can hope that the JVM can perform some optimization.

For code that needs to do the job in 5 min coding, the above snippet is more than perfectly fine, but for a library an extra effort can be done.

Provide the feature

Optimization is the root of all evil. as said Donald Knuth

The real problem is that programmers have spent far too much time worrying about efficiency in the wrong places and at the wrong times; premature optimization is the root of all evil (or at least most of it) in programming. We focus to provide the feature first. If some optimization can be done, it will be done after.

The library focus on delivering features to programmers. Optimization could be done afterward.

Not just String

The String is the cornerstone of Java and until now it serves us very well.

The library wants to be more flexible and allows comparison of objects that implements the CharSquence interface. This allows to to be able to compare CharBuffer, StringBuilder, String and others without converting them prior to String.