Data Gathering in Preparation for Baptism

How does one go from this:

Solution 1
public int compareTo(SelectionRecord that) {
  if(this.source.compareTo(that.source) == 0) {
	if (this.key.compareTo(that.key) == 0) {
		return this.activity.compareTo(that.activity);
	}
	return this.key.compareTo(that.key);
   }
	return this.source.compareTo(that.source);
}

to this:

Solution 2
		public int compareTo(SelectionRecord that) {
			return new CompareToBuilder()
			.append(this.source, that.source)
			.append(this.key, that.key)
			.append(this.activity, that.activity)
			.toComparison();
		}

Did you know about CompareToBuilder? If yes, how did you find out and have you ever used it?

In my never ending quest to become a “Code Complete”-toting member of the Church of Geek, I am forever seeking to understand how the Elders of the Church of Geek acquire their wisdom. The code snippets above, will illustrate my current mulling.

Last Friday, we wrote a compareTo method to ensure that a list of records will be returned sorted by their source, key and activitiy fields respectively. I must confess that the first pass was kind of unpleasant looking, so we settled on Solution 1 above, which we thought was quite elegant and called the task done. In fact, compared to what was there before it, Solution 1 was so aesthetically pleasing to the eye, that I sat back and revelled in its beauty for a few moments.

At 5:55pm, in waltzes a revered Elder of the Church who, in the span of ten minutes, replaces our better-than-sliced-bread solution with Solution 2 and opens my eyes to the wonders of the EqualsBuilder, HashCodeBuilder and the ToStringBuilder!

I was left in awe and despair. Awe:- in the simplicity of the solution; despair:- about how clearly my satisfaction with the first solution separated me from the the Elders of the Church of Geek. So, I performed a mini-experiment to alleviate this sinking feeling of never catching up. I asked another Elder of the Church if he knew about it. He was aware of the Builders but had never used them. He only knew about it because he happened to stumble upon it whilst looking for something else.

So the data gathering continues. I am almost certain that had he not used the apache commons tools, the Elder’s solution would have been quite similar to ours. Although this may seem like a trivial example, I believe it serves a good purpose to facilitate my data-gathering process of how the Elders acquire their knowledge and wisdom in Church of Geek.

So, how did you come across the Builder classes? Did you see it in a blog or newsletter you subscribe to? Did you discover it through pairing like I did or did you go Googling for it in search of an elegant solution?

It's only fair to share...
Share on FacebookGoogle+Tweet about this on TwitterShare on LinkedIn

Leave a Reply