轉載自:http://blog.csdn.net/linsheng9731/article/details/39637323#comments
一、簡化條件表達式
這個是幾乎所有的工程都會存在的問題,不當的條件表達式造成代碼的冗餘。
下面我們列出普遍的問題,並給出一般的應對方法。
【1】條件判斷過長,表達不清晰。
- if((i!=0&&i == m_nDClickIndex[1])&&(m_nDClickIndex[1]!=m_nDClickIndex[0]))
- { .... }
- #define TrangelPos (i!=0&&i == m_nDClickIndex[1])&&(m_nDClickIndex[1]!=m_nDClickIndex[0])
- if(TrangelPos)
- ..................
【2】檢查條件不同,最終處理的行爲一致。
- if (header == "業務操作日誌")
- {
- OperationLog operationLog = new OperationLog();
- operationLog.Show();
- this.Close();
- }
- else if (header == "就業幫扶")
- {
- JobHelp jobhelp = new JobHelp();
- jobhelp.Show();
- this.Close();
- }
- else if (header == "統計報表")
- {
- ReportStatistics reportStatistics = new ReportStatistics();
- reportStatistics.Show();
- this.Close();
- }
- private UserControl ItemFactory(String header)
- {
- if (header == "就業協議書鑑證")
- return new JobCertificationShow();
- else if (header == "畢業生就業調整")
- return new EmploymentAdjustShow();
- else if (header == "成教生業務")
- return new AEStudentsCheckInShow();
- }
- UserControl SelectedItem=ItemFactory(header);
- if(SelectedItem!=null)
- SelectedItem.Show();
- this.close();
【3】大量使用控制標記。
- for(int i=0;i<len;i++)
- {
- if(!found)
- {
- if(...)
- {
- found=true;
- }
- }
- }
解決辦法:用break或者是continue來取代標記。
- for(int i=0;i<len;i++)
- {
- if(...)
- {
- break;
- }
- }
【4】大量的判斷條件的嵌套
- if(...)
- result=...;
- else if(...)
- result=...;
- else
- {
- if(...)
- result=...;
- }
- return result;
解決辦法:大量的嵌套導致表達不清,用衛語句去除嵌套。
- if(....) return ....
- else if(...) return...
- else return ....
【5】使用類型碼區分不同的類型
- switch(type){
- case 1: return getBase1();
- case 2: return getBase2();
- case 3: return getBase3();
- case 4: return getBase4();
- }
- shape{
- draw();
- }
- Trangel extends shape{
- draw()
- {
- .....
- }
- }
- Rectangel extends shape{
- draw()
- {
- .....
- }
- }
- Circel extends shape{
- draw()
- {
- .....
- }
- }
- shape b;
- b=new Trangel(0;
- b.draw();//三角形
- b=new Rectangel();
- b.draw();//矩形
- b=new Circel();//圓形
- b.draw();
【6】對null對象的大量判斷
- object=getobject();
- if(objct!=null) object.action();
- else ...
解決辦法:定義一個object 對應的 null 對象。使得null 對象和object 對象的行爲統一。
- getobject()
- {
- if(this==null)
- return nullobject;
- return object;
- }
- nullobject{
- action()
- {
- ........
- }
- }
- object = getobject();
- object.action();