Two succinct code refactorings in Java.

Overview

Given a long career in Java programming one ought to have encountered many surprise techniques in programming language syntax that reduces lines of code without sacrificing the correctness of the program. I have certainly come across many such gems in my career but below I am going to show two techniques that I particularly like.

1. Instantiation and member function Initialization

// verbose: traditional way of instantiating the
// subclass and then
// setting the individual
// member values in separate set of steps
Person a = new Student("abc123");
a.setAge(24);
a.setFirstName("Abra");
a.setLastName("Cadabra");

// succinct: Instantiate
// and set the member values at once
Person b = new Student("abc123"){ {
    setAge(24);
    setFirstName("Abra");
    setLastName("Cadabra");
} };

2. Sorting Collections

//Initialized using the succinct technique from 1.
List<Integer> ages = new ArrayList<Integer>(){ {
   add(12);
   add(32);
   add(5);
   add(3);
} };

//verbose: sort ascending order
Collections.sort(ages, new Comparator<Integer>(){

    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
    }
});

//verbose: sort descending order
Collections.sort(ages, new Comparator<Integer>(){

    @Override
    public int compare(Integer o1, Integer o2) {
        return o2.compareTo(o1);
    }
});

//succinct: sort ascending order
Collections.sort(ages,
 Collections.<Integer>reverseOrder
 	(Collections.<Integer>reverseOrder()));

//succinct: sort descending order
Collections.sort(ages,
 Collections.<Integer>reverseOrder());

Epilogue

That’s all folks! I hope you enjoyed reading about these two techniques as much as I enjoyed writing.