aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/sorting/AbstractCacheComparator.java
blob: d7c46e19ccc02682fa208e4c56d3b92ec8e2ba71 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package cgeo.geocaching.sorting;

import cgeo.geocaching.Geocache;
import cgeo.geocaching.utils.Log;

import org.apache.commons.lang3.StringUtils;

/**
 * abstract super implementation for all cache comparators
 *
 */
abstract class AbstractCacheComparator implements CacheComparator {

    @Override
    public final int compare(final Geocache cache1, final Geocache cache2) {
        try {
            final boolean canCompare1 = canCompare(cache1);
            final boolean canCompare2 = canCompare(cache2);
            if (!canCompare1) {
                return canCompare2 ? 1 : fallbackToGeocode(cache1, cache2);
            }
            return canCompare2 ? compareCaches(cache1, cache2) : -1;
        } catch (final Exception e) {
            Log.e("AbstractCacheComparator.compare", e);
            // This may violate the Comparator interface if the exception is not systematic.
            return fallbackToGeocode(cache1, cache2);
        }
    }

    private static int fallbackToGeocode(final Geocache cache1, final Geocache cache2) {
        return StringUtils.defaultString(cache1.getGeocode()).compareToIgnoreCase(StringUtils.defaultString(cache2.getGeocode()));
    }

    /**
     * Check necessary preconditions (like missing fields) before running the comparison itself.
     * Caches not filling the conditions will be placed last, sorted by Geocode.
     *
     * The default implementation returns <code>true</code> and can be overridden if needed in sub classes.
     * 
     * @param cache
     *            the cache to be sorted
     *
     * @return <code>true</code> if the cache holds the necessary data to be compared meaningfully
     */
    @SuppressWarnings("static-method")
    protected boolean canCompare(final Geocache cache) {
        return true;
    }

    /**
     * Compares two caches. Logging and exception handling is implemented outside this method already.
     * <p/>
     * A cache is smaller than another cache if it is desirable to show it first when presented to the user.
     * For example, a highly rated cache must be considered smaller than a poorly rated one.
     *
     * @return an integer < 0 if cache1 is less than cache2, 0 if they are equal, and > 0 if cache1 is greater than
     *         cache2.
     */
    protected abstract int compareCaches(final Geocache cache1, final Geocache cache2);

}