# 重构笔记——提取方法（Extract Method）

```public void printOwing() {
double outstanding = 0.0;
Enumeration e = _orders.elements();

System.out.println("****************************");
System.out.println("******* Customer Owes ******");
System.out.println("****************************");

while (e.hasMoreElements()) {
Order v = (Order) e.nextElement();
outstanding += v.getAmount();
}

// print result
System.out.println("name: " + _name);
System.out.println("amount: " + outstanding);
}```

```public void printOwing() {
double outstanding = 0.0;
Enumeration e = _orders.elements();

printBanner();

while (e.hasMoreElements()) {
Order v = (Order) e.nextElement();
outstanding += v.getAmount();
}

System.out.println("name: " + _name);
System.out.println("amount: " + outstanding);
}

public void printBanner() {
System.out.println("****************************");
System.out.println("******* Customer Owes ******");
System.out.println("****************************");
}```

```public void printOwing() {
double outstanding = 0.0;
Enumeration e = _orders.elements();

printBanner();

// calculate outstanding
while (e.hasMoreElements()) {
Order v = (Order) e.nextElement();
outstanding += v.getAmount();
}

printDetails(outstanding);
}

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

public void printDetails(double outstanding) {
System.out.println("name: " + _name);
System.out.println("amount: " + outstanding);
}```

```public void printOwing() {
printBanner();
double outstanding = getOutstanding();
printDetails(outstanding);
}

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

public void printDetails(double outstanding) {
System.out.println("name: " + _name);
System.out.println("amount: " + outstanding);
}

public double getOutstanding() {
double outstanding = 0.0;
Enumeration e = _orders.elements();

while (e.hasMoreElements()) {
Order v = (Order) e.nextElement();
outstanding += v.getAmount();
}
return outstanding;
}```

1.每个方法足够细粒度，那么就很方便进行代码复用

2.高层次的方法阅读的时候就像注释一样清晰明了

3.如果方法都是细粒度，方法的复写也会变得更容易一些

• 0

开心

• 0

板砖

• 0

感动

• 0

有用

• 0

疑问

• 0

难过

• 0

无聊

• 0

震惊

1.概述 在软件系统中，经常面临着“某个对象”的创建工作，由于需求的变化，这个对象的具体实现经常