mardi 1 janvier 2019

The clear way to validate a file

I have to validate the path for a file received as input from user. My problem is that I have to use too many "if" and in my opinion the code looks a bit messy. I know that I can to evitate this conditional statements by using the pattern "chain of responsibility", but this aproch seems to be a bit too complicated for my problem. I mean, I dont't really want to make a new class for each validation.

Here is my code:

public boolean isValidFile(String filePath) {
    File file = new File(filePath);
    if(!getFileExtension(file).equals("txt")) {
        return false;
    }
    if(!file.exists()) {
        return false;
    }
    if(!file.isFile()) {
        return false;
    }
    if(file.isHidden()) {
        return false;
    }
    if(!file.canRead()) {
        return false;
    }
    if(!file.canExecute()) {
        return false;
    }

    return true;
}

Any suggestions?

Aucun commentaire:

Enregistrer un commentaire