我应该避免在我的代码中有很长的序列化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