John R.
John R.

Reputation: 420

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.canExecute()) {
        return false;
    }
    if(!file.canRead()) {
        return false;
    }

    return true;
}

Any suggestions?

Upvotes: 2

Views: 111

Answers (3)

Federico Terzi
Federico Terzi

Reputation: 101

I think your method is pretty good for what you want to achieve.

Trying to make it more compact is possible using boolean operators ( || and && ) but I think that the decreased readability is much worse than verbosity.

Chain of responsability is totally overkill for this kind of problem in my opinion.

Upvotes: 0

kabanus
kabanus

Reputation: 25980

This may be opinion based, and your function is quite readable (in my opinion...), but some other options open for you:

if(!getFileExtension(file).equals("txt")) return false;
if(!file.exists()) return false;
...

or

if(!getFileExtension(file).equals("txt") ||
   !file.exists() ||
   ...
   !file.canRead()) return false;

or

return (
   getFileExtension(file).equals("txt") &&
   file.exists() &&
   ...
   file.canRead());

which may be a more direct way of writing the requirement for a valid file.

Upvotes: 2

Jonas Wilms
Jonas Wilms

Reputation: 138537

You could use boolean algebra:

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

Upvotes: 2

Related Questions