代碼重構與優化

在軟件開發過程中經常遇到這樣的一件事就是,昨天寫的代碼今天就讀不懂了.這很大的一個原因就是代碼沒有寫註釋和代碼太長和邏輯很亂.前幾天我看一項目中一個同事寫的代碼....

public String getSql(final String code, final String name, final String type) {
  // TODO Auto-generated method stub
  StringBuffer sb = new StringBuffer("select count(labo.id)  from CntCodeValueBO cnt, MdProcLabelBO labo where  ");
  if (type != null) {
   if (type.equals("")) {
    sb.append(" labo.typeId like '%" + type + "%' ");
   } else {
    sb.append(" labo.typeId = '" + type + "' ");
   }
   if (code != null) {
    sb.append(" and labo.code like '%" + code + "%'");
   }
   if (name != null) {
    sb.append(" and labo.name like '%" + name + "%'");
   }
   sb.append("and cnt.codeTypeId=21 and labo.typeId=cnt.key order by labo.id ");
  } else {
   if (code != null) {
    sb.append(" labo.code like '%" + code + "%'");
    if (name != null) {
     sb.append(" and labo.name like '%" + name + "%'");
    }
    sb.append("and cnt.codeTypeId=21 and labo.typeId=cnt.key ");
   } else {
    if (name != null) {
     sb.append(" labo.name like '%" + name + "%'");
     sb.append("and cnt.codeTypeId=21 and labo.typeId=cnt.key order by labo.id ");
    } else {
     sb.append(" cnt.codeTypeId=21 and labo.typeId=cnt.key ");
    }
   }
  }
  return sb.toString();
 }

是不是很驚歎一個方法中有7個IF 4個 ELSE 邏輯是不是很亂.不易讀吧,據重構:改善既有代碼的設計一書的思想:可用方法代替IF重構代碼爲:

public String getSql(final String code, final String name, final String type){
  StringBuffer sql = new StringBuffer("select count(labo.id)  from CntCodeValueBO cnt, MdProcLabelBO labo where  ");
  sql.append(checkType(type)+checkCode(code)+checkName(name)+" order by labo.id ");
  return sql.toString();
 }
 public String codeNoNull(String code){
  return  "and labo.code like '%" + code + "%' ";
 }
 public String nameNoNull(String name){
  return " and labo.name like '%" + name + "%' ";
 }
 public String typeNoNullAndValue(String type){
  return " cnt.codeTypeId=21 and labo.typeId=cnt.key labo.typeId like '%" + type + "%' ";
 }
 public String typeNoNullNoValue(String type){
  return " cnt.codeTypeId=21 and labo.typeId=cnt.key labo.typeId = '" + type + "' ";
 }
 public String checkType(final String type){
  if(type != null && type.equals(""))return typeNoNullNoValue(type);
  if(type != null) return typeNoNullAndValue(type);
  return " cnt.codeTypeId=21 and labo.typeId=cnt.key ";
 }
 public String checkCode(final String code){
  if(code != null) return codeNoNull(code);
  else return "";
 }
 public String checkName(final String name){
  if(name != null) return nameNoNull(name);
  else return "";
 }

這樣代碼就易讀易維護多了...

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章