# 优化代码的几个小技巧

## 提炼函数（适当抽取小函数）

### 优化例子

``````    private String name;
private Vector<Order> orders = new Vector<Order>();

public void printOwing() {
//print banner
System.out.println("****************");
System.out.println("*****customer Owes *****");
System.out.println("****************");

//calculate totalAmount
Enumeration env = orders.elements();
double totalAmount = 0.0;
while (env.hasMoreElements()) {
Order order = (Order) env.nextElement();
totalAmount += order.getAmout();
}

//print details
System.out.println("name:" + name);
System.out.println("amount:" + totalAmount);
}

``````    private String name;
private Vector<Order> orders = new Vector<Order>();

public void printOwing() {

//print banner
printBanner();
//calculate totalAmount
double totalAmount = getTotalAmount();
//print details
printDetail(totalAmount);
}

void printBanner(){
System.out.println("****************");
System.out.println("*****customer Owes *****");
System.out.println("****************");
}

double getTotalAmount(){
Enumeration env = orders.elements();
double totalAmount = 0.0;
while (env.hasMoreElements()) {
Order order = (Order) env.nextElement();
totalAmount += order.getAmout();
}
}

void printDetail(double totalAmount){
System.out.println("name:" + name);
System.out.println("amount:" + totalAmount);
}

## 内联函数（适当去除多余函数）

### 优化例子

``````    int getRating(){
return moreThanFiveDeliveries() ? 2 : 1;
}
boolean moreThanFiveDeliveries(){
return numberOfLateDeliveries >5;
}

``````  int getRating(){
return numberOfLateDeliveries >5 ? 2 : 1;
}

## 内联临时变量（去除多余临时变量）

### 优化例子

``````double basePice = anOrder.basePrice();
return basePice >888;

`````` return anOrder.basePrice() >888;

## 引入解释性变量

### 优化例子

``````if ((platform.toUpperCase().indexOf("mac") > -1) &&
(brower.toUpperCase().indexOf("ie") > -1) &&
wasInitializes() && resize > 0) {
......
}

``````final boolean isMacOS = platform.toUpperCase().indexOf("mac") > -1;
final boolean isIEBrowser = brower.toUpperCase().indexOf("ie") > -1;
final boolean wasResized = resize > 0;

if (isMacOS && isIEBrowser && wasInitializes() && wasResized) {
......
}

## 以字面常量取代魔法数

### 优化例子

``````double getDiscountPrice(double price){
return price * 0.88;
}

`````` static final double DISCOUNT_CONSTANT=0.88;

double getDiscountPrice(double price){
return price * DISCOUNT_CONSTANT;
}

## 用多态替代switch语句

### 优化例子

`````` int getArea() {
switch (shape){
case SHAPE.CIRCLE:
return 3.14 * _r * _r; break;
case SHAPE.RECTANGEL;
return width *,heigth;
}
}

`````` class Shape {
int getArea(){};
}

class Circle extends Shape {
int getArea() {
return 3.14 * r * r;
}
}

class Rectangel extends Shape {
int getArea() {
return width * heigth;
}
}

## 将过多的参数对象化

### 优化例子

``````public int register(String username,String password,Integer age,String phone);

`````` public int register(RegisterForm from );

class RegisterForm{