if
1
public void showInfo(){
boolean isChecked = true; //
if (isChecked) {
nameTV.setText(name);
return;
}
ageTV.setText(age);
}
上面寫法是一種很好的寫法,後續維護很好,可是會給人一種定性思維,在複用的時候容易出錯,比如,習慣這樣寫了,在複用的時候,如果else,那麼nameTV就是之前的值,顯示就出問題了
2
首先要判斷一個標記,在遍歷一個循環,如果標記不滿足,或者遍歷對象爲空,則執行默認處理。
例如先判斷showType是否有值,如果有,則循環showTypeList,把出現了的type都設置爲選中,否則,把所有這個box給選中
String showTypeRadioButtonName = null;
if (StringUtils.hasText(showType)) {
String[] showTypes = showType.split(","); // 以,分隔
Collections.addAll(showTypeList, showTypes);
for (String showType : showTypeList) {
showTypeRadioButtonName = showTypeRadioButtonNamePre + showType;
int showTypeRadioButtonId = getResources().getIdentifier(showTypeRadioButtonName, "id", MainApplication.PACKAGE_NAME);
CheckBox checkBox = (CheckBox) view.findViewById(showTypeRadioButtonId);
if (checkBox != null) {
checkBox.setChecked(true);
}
}
}
if (!StringUtils.hasText(showTypeRadioButtonName)) { // 如果showTypeRadioButtonName爲空,則沒有經歷for循環中的賦值,執行默認處理
showTypeRadioButtonName = showTypeRadioButtonNamePre + Extends.SHOWTYPE_ALL;
int showTypeRadioButtonId = getResources().getIdentifier(showTypeRadioButtonName, "id", MainApplication.PACKAGE_NAME);
CheckBox checkBox = (CheckBox) view.findViewById(showTypeRadioButtonId);
if (checkBox != null) {
checkBox.setChecked(true);
}
}
統一處理
一個常見的寫法是把該功能封裝成方法,然後各處調用,如果只有一種那還好,如果有多種,比如,showHead, showContent,showFooter, 然後,該方法在各種地方調用,例如onStart, activityResult,onEventBus,等,這裏建議,發送handler,交給handler統一處理,雖然這樣在查找的時候只是比直接調用好那麼一點點,但仍然建議這樣做
註釋
當修改一段邏輯的時候,最好註釋中寫明白,爲什麼要這樣修改
例如,有一個view顯示名字,但是對象中有userName和niceName,
那麼用哪個顯示,爲什麼要用這個?
我這裏遇到的問題是,原先邏輯是:有niceName用niceName,否則用userName
後來被人改成了用userName,
再後來顯示一串無意義的數字,似乎又要改回原有邏輯,可是之前的修改是一個離職人員寫的,so,根本不知道爲啥要這樣修改,正巧,相關人員又請年假回家了,這…