转载自: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();