当我们创建一个返回布尔值的函数时,我们是否应该返回每个if/else语句?我们应该使用`else return`还是`return`?
例如,如果你想检查一个文件中迅速存在,你会做
func fileExists() -> Bool
{
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
{
let path = dir.appendingPathComponent("\(self.name).\(self.type)")
if(FileManager.default.fileExists(atPath: path.path))
{
return true
}
}
return false
}
的问题是,我们应该在函数的末尾添加return false
如果条件得到满足,如图以上,还是应该在每个if
statment添加return false
(如下图所示)
func fileExists() -> Bool
{
if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
{
let path = dir.appendingPathComponent("\(self.name).\(self.type)")
if(FileManager.default.fileExists(atPath: path.path))
{
return true
} else {
return false
}
} else {
return false
}
}
对我来说,第一个例子看上去干净,但我不知道这是很好的做法。尽管它看起来更干净,但我想用最好/最安全的方式,所以这个问题并不是对看起来最好的看法。
此问题语言特定?如果是这样,请添加合适的语言标签。 – Quentin
@Quentin这不是语言特定的。我想知道其他语言,因为我也使用java。给出的例子只是因为我当时正在研究这个项目。 – iProgram
请看这里http://refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html –