几个简单代码优化方法
提取代码
提取前
void renderBanner() {
if ((platform.toUpperCase().indexOf("MAC") > -1) &&
(browser.toUpperCase().indexOf("IE") > -1) &&
wasInitialized() && resize > 0 )
{
// do something
}
}
提取后
void renderBanner() {
final boolean isMacOs = platform.toUpperCase().indexOf("MAC") > -1;
final boolean isIE = browser.toUpperCase().indexOf("IE") > -1;
final boolean wasResized = resize > 0;
if (isMacOs && isIE && wasInitialized() && wasResized) {
// do something
}
}
Inline Temp
内联变量之前,减少代码量,方便查看。
double hasDiscount(Order order) {
double basePrice = order.basePrice();
return (basePrice > 1000);
}
内联变量之后
double hasDiscount(Order order) {
return (order.basePrice() > 1000);
}
Replace Temp with Query
用变量取代查询之前
double calculateTotal() {
double basePrice = quantity * itemPrice;
if (basePrice > 1000) {
return basePrice * 0.95;
}
else {
return basePrice * 0.98;
}
}
用变量之后,读起来更有目的性
double calculateTotal() {
if (basePrice() > 1000) {
return basePrice() * 0.95;
}
else {
return basePrice() * 0.98;
}
}
double basePrice() {
return quantity * itemPrice;
}
Substitute Algorithm
用算法替代之前
string FoundPerson(string[] people)
{
for (int i = 0; i < people.Length; i++)
{
if (people[i].Equals("Don"))
{
return "Don";
}
if (people[i].Equals("John"))
{
return "John";
}
if (people[i].Equals("Kent"))
{
return "Kent";
}
}
return String.Empty;
}
用算法替代之后
string FoundPerson(string[] people)
{
List<string> candidates = new List<string>() {"Don", "John", "Kent"};
for (int i = 0; i < people.Length; i++)
{
if (candidates.Contains(people[i]))
{
return people[i];
}
}
return String.Empty;