lundi 2 janvier 2017

Should we use `else return` or `return`?

When we make a function that returns a boolean, should we return on every if/else statment or not?

For example, if you wanted to check that a file existed in swift, you would do

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
}

The question is, should we add return false at the end of the function if the condition was met as shown above, or should we add return false on each if statment (shown below)

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
    }
}

To me, the first example looks cleaner, however I am not sure that this is good practice. Even though it looks cleaner, I would like to use the best/safest way instead, so this question is not an opinion on what looks the best.

Aucun commentaire:

Enregistrer un commentaire