应该把代码组织得一次只做一件事,任务可以很小
vote_changed(old_vote, new_vote); // each vote is "Up", "Down", or "" 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); }; //上面的代码有一些错综复杂的细节,看上去只做了一件事,实际上做了两件事情。 // 1. 把old_vote 和 new_vote解析成数字 // 2. 更新分数 var vote_value = function (vote) { if (vote === 'Up') { return +1; } if (vote === 'Down') { return -1; } return 0; }; 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); };