标签:arc tin iterator mat 一段 logs 技巧 变量定义 object
代码并非一開始就变坏,代码变坏有下面可能
1、需求变更
2、维护代码的人的水平參差不齐
3、维护人员流动大
4、开发周期短,交付时间紧急
5、个人习惯
6、管理者对代码的要求
以上都是有可能使代码变坏的可能,那么怎样写出好的代码?除了个人编程能力外还须要有一定的技巧,下面就是总结前人的经验
得来的,须要在编程中养成一种好习惯。让写好代码成为一种习惯吧!
!!
!
。
1、使用卫语句
在什么情况下能够使用卫语句呢,例如以下
public void add(Object element) { if (!readOnly) { int newSize = size + 1; if (newSize > elements.length) { Object[] newElement = new Object[elements.length + 10]; for (int i = 0; i < size; i++) { newElements[i] = elements[i]; } elements = newElements; } elements[size++] = element; } }使用卫语句重构后。例如以下
public void add(Object element) { if (readOnly) return; int newSize = size + 1; if (newSize > elements.length) { Object[] newElement = new Object[elements.length + 10]; for (int i = 0; i < size; i++) { newElements[i] = elements[i]; } elements = newElements; } elements[size++] = element; }这样嵌套就少了一层,减少复杂度
public List getUsers(){ List users = new ArrayList<User>(); //......... //sort by most recently registered users Collections.sort(users, new User.UserComparatorByDescendingRegistration()); return users; }提炼方法之后
public List getUsers(){ List users = new ArrayList<User>(); //......... sortByMostRecentlyRegistered(users); return users; }三、函数结构层次单一,例如以下
void printOwing(double amount){ printBanner(); System.out.println("name:" + _name); System.out.println("amount" + amount); }重构后
void printOwing(double amount){ printBanner(); printDetails(amount); }
public double getPrice(){ double basePrice = _quantity*_itemPrice; if (basePrice > 1000){ return basePrice * 0.95; }else{ return basePrice * 0.98; } }重构后代码
public double getPrice(){ if (BasePrice() > 1000){ return BasePrice() * 0.95; }else{ return BasePrice() * 0.98; } } private int BasePrice(){ return _quantity* _itemPrice; }3、变量作用单一,例如以下代码的avg有两个作用,意义不明白,easy产生岐义
private double calculateAverage(){ Iterator grades = clines.iterator(); double avg = 0.0; while(grades.hasNext()){ grade = (CourseGrade)grades.next(); if(!(grade.grade == "F")){ avg = avg + grade.grade - 64; } } avg = avg / clines.size(); return avg; }4、又一次组织代码,变量定义与使用的跨度不要过大。即在使用时再定义,更easy理解
MARKETING_DATA *marketingData = new MARKETING_DATA; SALES_DATA *salesData = new SALES_DATA; TRAVEL_DATA *travelData = new TRAVEL_DATA; travelData.ComputeQuarterly(); salesData.ComputeQuarterly(); marketingData.ComputeQuarterly(); salesData.ComputeAnnual(); marketingData.ComputeAnnual(); travelData.ComputeAnnual(); salesData.print(); travelData.print(); marketingData.print();重构后代码
MARKETING_DATA *marketingData = new MARKETING_DATA; marketingData.ComputeQuarterly(); marketingData.ComputeAnnual(); SALES_DATA *salesData = new SALES_DATA; salesData.ComputeQuarterly(); salesData.ComputeAnnual(); salesData.print(); TRAVEL_DATA *travelData = new TRAVEL_DATA; travelData.ComputeQuarterly(); travelData.ComputeAnnual(); travelData.print();
1、http://www.cnblogs.com/matchcolor/archive/2010/08/02/1784888.html
标签:arc tin iterator mat 一段 logs 技巧 变量定义 object
原文地址:http://www.cnblogs.com/jzssuanfa/p/6816525.html