TIP: Stuff That Still Bites You Even When You Have Grey Hairs
I am going to put stuff here every-time I repeat an old error in coding technique so that perhaps I will remember this gotcha next time and avoid it!
PROBLEM: FORGETTING A BREAK
Forgetting a break in a switch leads to wrong radio button being set since the call FALLS THROUGH.
switch(timeoutType) {
case TIMEOUT_NEVER:
radioGroupTimeout.check(R.id.radio_never);
break;
case TIMEOUT_MONTHLY:
radioGroupTimeout.check(R.id.radio_monthly);
break;
case TIMEOUT_DAILY:
radioGroupTimeout.check(R.id.radio_daily); // big boo boo here
case TIMEOUT_HOURLY:
radioGroupTimeout.check(R.id.radio_hourly);
break;
}
SOLUTION: PUT IN THE BREAK BEFORE THE CODE
And if you intend for the fall through, comment the fall through.
switch(timeoutType) {
case TIMEOUT_NEVER:
break;
case TIMEOUT_MONTHLY:
break;
case TIMEOUT_DAILY:
break;
case TIMEOUT_HOURLY:
break;
}
PROBLEM: DOING INTEGER MATH ON A LONG RESULT
Forgetting that math is done on integers by default, causing a math error.
private static final long LONG_YEAR_MILLIS= (365*24*60*60*1000); // big boo boo here
This cause an overflow and the wrong answer! If you want an long result, use longs as input:
private static final long LONG_YEAR_MILLIS= (365L*24L*60L*60L*1000L);
SOLUTION: WHEN YOU TYPE *, THINK * WHAT!
PROBLEM: FAILING TO SEE THE OBVIOUS
if (isSomeState) {
checkBox.setChecked(true);
else {
checkBox.setChecked(false);
}
Can be replaced by:
checkBox.setChecked(isSomeState);
Doh!
PROBLEM: FAILING TO TRUST SHORT CIRCUITED && and ||
Java has the two short-circuited operators && and || which do not evaluate the second operand if the first operand returns true. So we can shorten:
if (eulaPrefs == null || (eulaPrefs != null && eulaPrefs.getBoolean(PREFERENCE_EULA_ACCEPTED, false) == false)) {
showDialog(DIALOG_EULA_ACCEPT);
} // short circuited OR
To:
if (eulaPrefs == null || (eulaPrefs.getBoolean(PREFERENCE_EULA_ACCEPTED, false) == false)) {
showDialog(DIALOG_EULA_ACCEPT);
} // short circuited OR
You can confirm this by setting eulaPrefs to null, running the code without seeing a nullpointerexception!
I hope this list saves you a few extra grey hairs,
JAL