我應該避免在我的代碼中有很長的序列化IF語句列表嗎?有時似乎不可避免,但我想知道這是否是我的缺乏經驗。我應該避免一長串IF聲明嗎?
例如,如果你正在處理圖像的用戶上傳了 - 你想給的任何錯誤,準確的反饋 - 你可能會碰到這樣的:
if($file["size"] == 0) {
throw new Exception("ERROR: File was empty");
}
if (($file["type"] != "image/gif")
|| ($file["type"] != "image/jpeg")
|| ($file["type"] != "image/pjpeg")
|| ($file["type"] != "image/png")) {
throw new Exception("ERROR: Image must be either GIF, PNG or JPEG!");
}
if ($file["size"] > 2000000) {
throw new Exception("ERROR: Image must be than less 2MB!");
}
if ($file["error"] > 0) {
throw new Exception("UNKNOWN ERROR: ".$file['error']);
}
$imgDetails = getimagesize($file["tmp_name"]);
if($imgDetails['channels'] != 3){
throw new Exception("ERROR: Image must be RGB.)";
}
if($imgDetails['0'] < 50 && $imgDetails['1'] < 50) {
throw new Exception("ERROR: Image must be larger then 50 x 50.)";
}
等等,等等等等直到最終文件通過所有測試並被處理。
這是「壞習慣」嗎?
這聽起來很明智! :)雖然我正在閱讀Exceptions,但這個博客讓我感到困惑。以上哪種類型的例外...? http://blogs.msdn.com/b/kcwalina/archive/2007/01/30/exceptionhierarchies.aspx – 2013-02-26 19:14:04
這取決於你想走多遠。如果你想做的只是傳遞一個消息,你可以放棄使用基本的異常類。設置異常類允許您以不同的方式處理每種類型的異常,這可能不是必需的。 – datasage 2013-02-26 19:17:42
謝謝,我已經更新了現在的問題 - 只是爲了好的措施:) – 2013-02-26 20:29:45