42. Case
if (mode ==
var a =
b =
minutes
"bustime") {
minutes % 10,
parseInt(minutes / 10);
= a != 0 ?
(a > 5 ?
(++b * 10) : b ?
(b * 10) : 5):
minutes;
Need Examples!
60. Problems
• More variables, harder to keep track of them
• Bigger variable’s scope, longer you have to keep
track of them
• More often variable changes, harder to keep
track of its current value
63. Case
var remove_one = function(array, value_to_remove) {
var index_to_remove = null;
for (var i = 0; i < array.length; i ++) {
if (array[i] === value_to_remove) {
index_to_remove = i;
break;
}
}
if (index_to_remove !== null) {
array.slice(index_to_remove, 1);
}
}
64. Case
var remove_one = function(array, value_to_remove) {
for (var i = 0; i < array.length; i ++) {
if (array[i] === value_to_remove) {
array.slice(i, 1);
return;
}
}
}
65. Shrink the Scope
• Make variable visible by as few lines of code
as possible.
66. Prefer write-once
variables
• KEY IDEA: The more places a variable is
manipulated, the harder it is to reason
about its current value.
69. Case
function findClosestLocation(latLng, latLngs) {
var closest;
var closest_dist = Number.MAX_VALUE;
for each latlng in latLngs, calculate the
distance, if new distance is shorter than
current, set closest to the new latlng
return closest;
}
70. What is the unrelated
subproblem?
Compute the
spherical distance
71. • Pure Utility Code
• General-Purpose Code
• Project-Specific Functionality
• Simplifying an Existing Interface
77. • Describe what code needs to do, in plain
English(we should use Chinese)
• Pay attention to key words and phrases
• Write your code to match description
78. Case
$is_admin = is_admin_request();
if ($document) {
if (!$is_admin
&& ($document['username']) != $_SESSION['username'])){
return not_authorized();
}
} else {
if (!$is_admin) {
return not_authorized();
}
}
// continue rendering the page ...
79. Case
if (is_admin_request()) {
// authorized
} elseif ($document
&& $document['username']) !=
$_SESSION['username'])) {
// authorized
} else {
return not_authorized();
}
// continue rendering the page ...