我一直在寫if語句,只要我在大學就讀我的第一個軟件類,最近我的同事已經引入了一種略有不同的方法來處理與出口而不是如果聲明包裝。我不確定哪種方法更好,希望聽到一些意見。嵌套if語句vs函數退出
如何我寫的東西(方案1):
function showLikesPopup($th) {
if ($th.find(".liked-times").text() !== "0") {
var $li = $th.parents(".comment-like");
if (!$li.find(".liked").length) {
var comment_id = $th.parents(".ci").data("comment-id");
var application_id = $th.parents(".ci").data("application-id");
var get_likes_url = url_to_current_unique + "/comments_module/get_comment_likes";
var aParams = {comment_id:comment_id,application_id:application_id};
if(!get_likes_request_started) {
get_likes_request_started = true;
ajaxRequest(
get_likes_url,
aParams,
function (response) {
$li.append(response.data.html);
$li.find(".liked").show();
get_likes_request_started = false;
}
);
}
}
$li.find(".liked").show();
}
}
如何我的團隊建議這被寫入(選項2):
function showLikesPopup($th) {
if ($th.find(".liked-times").text() === "0") {
return;
}
var $li = $th.parents(".comment-like");
if ($li.find(".liked").length) {
$li.find(".liked").show();
return;
}
if (get_likes_request_started) {
return;
}
var comment_id = $th.parents(".ci").data("comment-id");
var application_id = $th.parents(".ci").data("application-id");
var get_likes_url = url_to_current_unique + "/comments_module/get_comment_likes";
var aParams = {comment_id:comment_id,application_id:application_id};
get_likes_request_started = true;
ajaxRequest(
get_likes_url,
aParams,
function (response) {
$li.append(response.data.html);
$li.find(".liked").show();
get_likes_request_started = false;
}
);
}
請投選項1或2?謝謝你們,我知道這兩種方式都可以工作,但在我承諾開始使用這種新風格之前,我想確保它是長期的良好實踐。
http://softwareengineering.stackexchange.com/questions/18454/should-i-return-from-a-function-early-or-use-an-if-statement – Bergi