Search code examples
javasonarqube

SonarQUBE and compareTo Dates


I got this Sonar Bug:

Use the original value instead. Rule: Neither "Math.abs" nor negation should be used on numbers that could be "MIN_VALUE"

in this method of compare date:

public int compareDates(MyDto a, MyDto b) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy hh:mm");
        try {
            Date dateA = sdf.parse(a.getStartDate() + " " + a.getStartHour());
            Date dateB = sdf.parse(b.getStartDate() + " " + b.getStartHour());
            return - dateA.compareTo(dateB); //Sonar BUG
        } catch (ParseException e) {
            logger.error("Unable to parse date: " + e.getMessage());
            return 0;
        }   
    }

I'm using this method to order collections of MyDto by date this way:

Collections.sort(myDtoList, (a,b) -> compareDates(a,b));

Now I really don't know what to do to amend. The integer given back from the compare can be negative or not, how can i solve to make SQ happy?


Solution

  • IMO this is almost as false positive.

    The result of dateA.compareTo(dateB) could conceivably be Integer.MIN_VALUE in which case -dateA.compareTo(dateB) would also evaluate to Integer.MIN_VALUE, thus not producing the result you want.

    Realistically that call is extremely likely to return either -1, 0 or 1 (i.e. it's not specified to only ever return those values, but all implementations of Date.compareTo() that I've seen do that).

    However there's a very easy way to avoid the negation (and thus this specific issue) entirely:

    Just return dateB.compareTo(dateA) if you want the opposite direction! Just swapping what you use as the arguments thas the same effect as negating the result, without the risk mentioned by sonar.