1.Eliminating Intermediate Results
//Here’s an example of a JavaScript function that removes a value from an array:
var remove_one = function (array, value_to_remove) {
var index_to_remove = null;
for (var i = 0; i < array.length; i += 1) {
if (array[i] === value_to_remove) {
index_to_remove = i;
break;
}
}
if (index_to_remove !== null) {
array.splice(index_to_remove, 1);
}
};
//sometimes be eliminated by handling the result as soon as you get it:
var remove_one = function (array, value_to_remove) {
for (var i = 0; i < array.length; i += 1) {
if (array[i] === value_to_remove) {
array.splice(i, 1);
return;
}
}
};
2. if Statement Scope in C++
//the person reading this
//code might keep info in mind, wondering if/how it will be used again.
PaymentInfo* info = database.ReadPaymentInfo();
if (info) {
cout << "User paid: " << info->amount() << endl;
}
// Many more lines of code below ...
//Now the reader can easily forget about info after it goes out of scope.
if (PaymentInfo* info = database.ReadPaymentInfo()) {
cout << "User paid: " << info->amount() << endl;
}
3. Shrink the Scope of Your Variables
//two methods, in the following way:
class LargeClass {
string str_;
void Method1() {
str_ = ...;
Method2();
}
void Method2() {
// Uses str_
}
// Lots of other methods that don't use str_ ...
};
//For this case, it may make sense to “demote” str_ to be a local variable:
class LargeClass {
void Method1() {
string str = ...;
Method2(str);
}
void Method2(string str) {
// Uses str
}
// Now other methods can't see str.
};