### 函数式编程的核心思想

``````String[] array = { "orange", "Pear", "Apple" };
Arrays.sort(array, String::compareToIgnoreCase);
``````

``````double calculateIncomeTax(IncomeRecord record) {
...
}
``````

``````class IncomeRecord {
String id; // 身份证号
String name; // 姓名
double salary; // 工资
}
``````

``````double calculateIncomeTax(IncomeRecord record) {
double threshold = 3500;
double tax = record.salary <= threshold ? 0 : (record.salary - threshold) * 0.2;
return tax;
}
``````

``````double calculateIncomeTax(IncomeRecord record) {
double threshold = today() < date(2018, 9, 1) ? 3500 : 5000;
double tax = record.salary <= threshold ? 0 : (record.salary - threshold) * 0.2;
return tax;
}
``````

`today()`这个函数，返回结果与时间有关，这就造成了`calculateIncomeTax()`不再是一个纯函数，它与当前时间相关了。

``````class IncomeRecord {
String id; // 身份证号
String name; // 姓名
double salary; // 工资
int year; // 年
int month; // 月
}
``````

``````double calculateIncomeTax(IncomeRecord record) {
double threshold = date(record.year, record.month) < date(2018, 9) ? 3500 : 5000;
double tax = record.salary <= threshold ? 0 : (record.salary - threshold) * 0.2;
return tax;
}
``````

`calculateIncomeTax()`又变成了一个纯函数，会计就不用改电脑时间了。

``````StockStatus process(StockStatus old, List<Order> orders) {
...
for (Order order : orders) {
...
sendExchangeResult(...); // 给每一笔成交发送信息
}
...
}
``````

Author: 廖雪峰

Publish at: ...