“I am sorry I have had to write you such a long letter, but I did not have time to write you a short one”
Pascal, Blaise (1623 – 1662) – French philosopher and mathematician.
At the age of 18 he invented the first calculating machine.
So I wonder why do we make the same mistake? Let’s review a few code examples.
Instead of following code:
private boolean isItemPutEligible( final SolrDocument doc) { String putEligibility = "N" ; Object obj = doc.getFieldValue(IS_PUT_ELIGIBLE); if (obj != null ) { putEligibility = obj.toString(); } if ( "Y" .equalsIgnoreCase(putEligibility)) { return true ; } return false ; } |
Could be shortened to:
private boolean isItemPutEligible( final SolrDocument doc) { Object obj = doc.getFieldValue(IS_PUT_ELIGIBLE); if (obj != null && obj.toString().toUpperCase().equals( "Y" )) { return true ; } return false ; } |
Instead of this code:
Object obj = doc.getFieldValue(PROD_ID); if (obj != null ) { if (obj instanceof ArrayList<?>) { ArrayList<?> al = (ArrayList<?>) obj; if (!al.isEmpty()) { Object o = al.get( 0 ); if (o != null ) { result = o.toString(); } } } else { result = obj.toString(); } } |
Could be shortened to:
Object obj = doc.getFirstValue(PROD_ID); if (obj!= null ) return obj.toString(); return null ; |
Both examples are much easier to read and understand I think.
In first instance we just avoid using unnecessary variable:
putEligibility
In second instance we used method that returns the very first value from List or Object found in document per field name or null:
getFirstValue
I think just reviewing such examples would inspire you to write less code and drink more of your favorite drink!!!