Salesforce summer’12 Sorting enhancements reviewed !

With force.com summer’12 release, I was very happy to see the ability to sort Non-primitive data types in apex with availability of List.sort() and Comparable fixture. Having native or system sorting support is great, but few gaps are their as well.

Goodness!

  • One no more needs to use hacks of creating primitive string keys for UDT(User Defined Types) and giving sorting support, this post shows one such hack.

  • Lesser consumption of script statements: As sorting will be done by native API, script statements wasted in comparisons and looping will not be counted in. But, please be careful with the “compareTo” method implementation, code in that method will add to script lines consumption during sorting operation. So if you are sorting a big collection, please keep eye on the compareTo() method.

Gaps

  • Sortable Class should be Global as well: “compareTo()” method is defined as global, thus Comparable interface implementation requires the apex class to be global, this doesn’t make any sense, to why something sortable should be global as well.

  • No easy way to sort on multiple attributes of a class: If we take the example of the Employee class below,

    global class Employee implements Comparable {
        public String name;
        public Integer age;
        public Date doj;
        
        public Employee (String n, Integer a, Date d) {
            this.name = n;
            this.age = a;
            this.doj = d;
        }
    
        // sort by age
        global Integer compareTo(Object other) {
            Integer otherAge = other != null ? ((Employee)other).age : 0;            
            return this.age - otherAge;
        }
    }
    
    

    Comparable gives a way to define natural ordering only, so in the above class using Comparable and no other hacks we can just sort on one attribute i.e. age. It would be nice to have support for the “Comparator” interface like java as well, so that sorting support can be easily added for other attributes as well, for ex. sort by doj or name. 

    • Side Update: In my next post, I will be covering how to sort multiple fields using a single comparable interface.

IdeaExchange

Posted an idea to fill these gaps in next force.com release. Please promote, if you also agree to these gaps.

Related reading

Your thoughts?

Looking forward for the same.

Abhinav Gupta

First Indian Salesforce MVP, rewarded Eight times in a row, has been blogging about Salesforce, Cloud, AI, & Web3 since 2011. Founded 1st Salesforce Dreamin event in India, called “Jaipur Dev Fest”. A seasoned speaker at Dreamforce, Dreamin events, & local meets. Author of many popular GitHub repos featured in official Salesforce blogs, newsletters, and books.

https://abhinav.fyi
Previous
Previous

Upcoming Salesforce Dev events in India (July’12)

Next
Next

Accessing Sobject Field Sets in Apex Code !