1.Extracting Values from an Object
var old = function () {
var place = location_info["LocalityName"]; // e.g. "Santa Monica"
if (!place) {
place = location_info["SubAdministrativeAreaName"]; // e.g. "Los Angeles"
}
if (!place) {
place = location_info["AdministrativeAreaName"]; // e.g. "California"
}
if (!place) {
place = "Middle-of-Nowhere";
}
if (location_info["CountryName"]) {
place += ", " + location_info["CountryName"]; // e.g. "USA"
} else {
place += ", Planet Earth";
}
return place;
}
//we rewrote the original code to solve each of these tasks independently.
var town = location_info["LocalityName"]; // e.g. "Santa Monica"
var city = location_info["SubAdministrativeAreaName"]; // e.g. "Los Angeles"
var state = location_info["AdministrativeAreaName"]; // e.g. "CA"
var country = location_info["CountryName"]; // e.g. "USA"
// Start with the default, and keep overwriting with the most specific value.
var RefactoredCode = function () {
var second_half = "Planet Earth";
if (country) {
second_half = country;
}
if (state && country === "USA") {
second_half = state;
}
var first_half = "Middle-of-Nowhere";
if (state && country !== "USA") {
first_half = state;
}
if (city) {
first_half = city;
}
if (town) {
first_half = town;
}
return first_half + ", " + second_half;
}
var RefactoredCode2 = function () {
var second_half = "Planet Earth";
if (country) {
second_half = country;
}
if (state && country === "USA") {
second_half = state;
}
var first_half = "Middle-of-Nowhere";
if (state && country !== "USA") {
first_half = state;
}
if (city) {
first_half = city;
}
if (town) {
first_half = town;
}
return first_half + ", " + second_half;
}
2. Tasks Can Be Small
/*
When the user clicks one of the buttons (to make/change her vote), the following JavaScript
is called:
vote_changed(old_vote, new_vote); // each vote is "Up", "Down", or ""
This function updates the total score and works for all combinations of old_vote/new_vote:*/
var vote_changed = function (old_vote, new_vote) {
var score = get_score();
if (new_vote !== old_vote) {
if (new_vote === 'Up') {
score += (old_vote === 'Down' ? 2 : 1);
} else if (new_vote === 'Down') {
score -= (old_vote === 'Up' ? 2 : 1);
} else if (new_vote === '') {
score += (old_vote === 'Up' ? -1 : 1);
}
}
set_score(score);
};
/*
We can make the code easier to read by solving each task separately. The following code solves
the first task, of parsing the vote into a numerical value:*/
var vote_value = function (vote) {
if (vote === 'Up') {
if (vote === 'Down') {
return -1;
}
return 0;
}
}
//Now the rest of the code can solve the second task, updating score:
var vote_changed = function (old_vote, new_vote) {
var score = get_score();
score -= vote_value(old_vote); // remove the old vote
score += vote_value(new_vote); // add the new vote
set_score(score);
}
/*As you can see, this version of the code takes a lot less mental effort to convince yourself that
it works. That’s a big part of what makes code “easy to understand.”*/