This article is a good reference from the art of writing readable code!
This article mainly introduces two ways to solve the problem ,,
- Reduces the number of nested layers. The nested layers undoubtedly increase the complexity of the Code.
- Return as early as possible, and process the judgment that can be processed as early as possible. Later corrections will make the code clearer.
For example, before reconstruction
public synchronized Drawable getAvatar(Context context, Drawable defaultValue) { if (mAvatar == null) { if (mAvatarData != null) { Bitmap b = BitmapFactory.decodeByteArray(mAvatarData, 0, mAvatarData.length); mAvatar = new BitmapDrawable(context.getResources(), b); } } return mAvatar != null ? mAvatar : defaultValue;}
The code above is difficult to see clearly at a glance, and the use of nesting increases the complexity of code reading.
After reconstruction:
public synchronized Drawable getAvatar2(Context context, Drawable defaultValue) {if (mAvatar != null) {return mAvatar;}if (mAvatarData == null) {return defaultValue;}Bitmap b = BitmapFactory.decodeByteArray(mAvatarData, 0, mAvatarData.length);mAvatar = new BitmapDrawable(context.getResources(), b);if (mAvatar == null) {return defaultValue;}return mAvatar;}
In addition, for the return in if else, there is no sense to perform else processing. If the conditions are met, You can directly use if. As follows:
private Contact getContactInfo(Contact c) { if (c.mIsMe) { return getContactInfoForSelf(); } else if (Mms.isEmailAddress(c.mNumber) || isAlphaNumber(c.mNumber)) { return getContactInfoForEmailAddress(c.mNumber); } else { return getContactInfoForPhoneNumber(c.mNumber); }}
After reconstruction:
private Contact getContactInfo(Contact c) {if (c.mIsMe) {return getContactInfoForSelf();}if (Mms.isEmailAddress(c.mNumber) || isAlphaNumber(c.mNumber)) {return getContactInfoForEmailAddress(c.mNumber);}return getContactInfoForPhoneNumber(c.mNumber);}