Core Java

Pitfalls of Java Comparable interface

JavaĀ ComparableĀ interface provides a way to do natural ordering for classes implementing the interface. Natural ordering makes sense for scalars and other quite simple objects, but when we come to more business oriented domain objects the natural ordering becomes much more complicated. A transaction object’s natural ordering from business manager’s point of view could be the value of the transaction, but from the system admin’s point of view the natural ordering could be the speed of the transaction. In most cases, there is no clear natural ordering for business domain objects.

Let’s assume that we have found a good natural ordering for a class likeĀ Company. We will use the company’s official name as the primary order field and the company id as the secondary. TheĀ CompanyĀ class’ implementation could be as follows.

public class Company implements Comparable<Company> {
 
    private final String id;
    private final String officialName;
 
    public Company(final String id, final String officialName) {
        this.id = id;
        this.officialName = officialName;
    }
 
    public String getId() {
        return id;
    }
 
    public String getOfficialName() {
        return officialName;
    }
 
    @Override
    public int hashCode() {
        HashCodeBuilder builder = new HashCodeBuilder(17, 29);
        builder.append(this.getId());
        builder.append(this.getOfficialName());
        return builder.toHashCode();
    }
 
    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Company)) {
            return false;
        }
        Company other = (Company) obj;
        EqualsBuilder builder = new EqualsBuilder();
        builder.append(this.getId(), other.getId());
        builder.append(this.getOfficialName(), other.getOfficialName());
        return builder.isEquals();
    }
 
    @Override
    public int compareTo(final Company obj) {
        CompareToBuilder builder = new CompareToBuilder();
        builder.append(this.getOfficialName(), obj.getOfficialName());
        builder.append(this.getId(), obj.getId());
        return builder.toComparison();
    }
}

The implementation looks fine and works properly. TheĀ CompanyĀ class isn’t enough for some use cases so we extend it to aĀ CompanyDetailsĀ class that provides more information about the company. Instances of these classes could be used for example in a data table showing details of companies.

public class CompanyDetails extends Company {
 
    private final String marketingName;
    private final Double marketValue;
 
    public CompanyDetails(final String id, final String officialName, final String marketingName, final Double marketValue) {
        super(id, officialName);
        this.marketingName = marketingName;
        this.marketValue = marketValue;
    }
 
    public String getMarketingName() {
        return marketingName;
    }
 
    public Double getMarketValue() {
        return marketValue;
    }
 
    @Override
    public int hashCode() {
        HashCodeBuilder builder = new HashCodeBuilder(19, 31);
        builder.appendSuper(super.hashCode());
        builder.append(this.getMarketingName());
        return builder.toHashCode();
    }
 
    @Override
    public boolean equals(final Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof CompanyDetails)) {
            return false;
        }
        CompanyDetails other = (CompanyDetails) obj;
        EqualsBuilder builder = new EqualsBuilder();
        builder.appendSuper(super.equals(obj));
        builder.append(this.getMarketingName(), other.getMarketingName());
        builder.append(this.getMarketValue(), other.getMarketValue());
        return builder.isEquals();
    }
}

Again the implementation looks fine at first glance, but actually it isn’t. We can create a small test case to indicate the issues of the implementation. The problem arises when we don’t know what the actual interface is doing with our class and we don’t pay enough attention to all details of the super class we are extending.

CompanyDetails c1 = new CompanyDetails("231412", "McDonalds Ltd", "McDonalds food factory", 120000.00);
CompanyDetails c2 = new CompanyDetails("231412", "McDonalds Ltd", "McDonalds restaurants", 60000.00);
 
Set<CompanyDetails> set1 = CompaniesFactory.createCompanies1();
set1.add(c1);
set1.add(c2);
 
Set<CompanyDetails> set2 = CompaniesFactory.createCompanies2();
set2.add(c1);
set2.add(c2);
 
Assert.assertEquals(set1.size(), set2.size());

We use two sets, but realize that they behave differently. Why is that? The other set is aĀ HashSetĀ that relies on the object’sĀ hashCode()Ā andĀ equals()Ā methods, but the other isĀ TreeSetĀ and relies only on theĀ ComparableĀ interface, which we didn’t implement for the subclass. This is quite common mistake when domain objects are extended, but more than that, this is about bad coding conventions. We usedĀ Apache Commonsā€˜ builders to implementĀ hashCode(),Ā equals()Ā andĀ compareTo()Ā methods. The builders supplyĀ appendSuper()Ā method that indicates that it should be used for the super class’ implementation for the method. If you have read the great bookĀ Effective JavaĀ by Joshua Bloch, you’d realize that this is not right. If we add fields in subclass, we cannot implementĀ equals()Ā orĀ compareTo()Ā methods properly without violating the symmetry rule. We should have used composition over inheritance. If we had used composition to create theĀ CompanyDetails, there would have been no issue for theĀ ComparableĀ interface, because we don’t implement it automatically and allow misbehavior by default. And also we could satisfy the requirements ofĀ equals()Ā andĀ hashCode()Ā properly.

The issues mentioned in this post are quite common but usually overlooked. The problems withĀ ComparableĀ interface actually arises from bad conventions and not understanding the requirements of the used interfaces. As a Java developer or architect, you should pay attention to things like this and obey good coding conventions and practices. The bigger the project, the more important it is to avoid errors created by the human factor. I tried to sum up a good best practices list forĀ ComparableĀ interface so the errors could be avoided.

Best practices for JavaĀ ComparableĀ interface design and usage:

  • Understand the domain object you are creating and if there is no clear natural ordering for the object, do not implementĀ ComparableĀ interface.
  • PreferĀ ComparatorĀ implementations overĀ Comparable.Ā ComparatorĀ can be used more business oriented way depending on the use case.
  • If you need to create interfaces or libraries that rely on comparing objects, provide your ownĀ ComparatorĀ implementation if possible, otherwise create good documentation how theĀ ComparatorĀ should be implemented for your interface.
  • Obey good coding conventions and practices. Effective Java is great book to start with.

 

Reference: Pitfalls of Java Comparable interface from our JCG partner Tapio Rautonen at the RAINBOW WORLDS blog.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Back to top button