Reputation: 458
I was writing a common function to check if the variable contains a file or a directory. So I came up with an idea to check it using a boolean return-type function. something like this :
function boolean checkFileOrDirectory(File myFile){
// Assume file already exist
if(myFile.isDirectory()){
//myFile is a directory
return true;
} else {
//myFile is a file
return false;
}
}
I was wondering about the accuracy of this function. I would really appreciate if anyone can tell me will there be any kind of file types which does not come under both isFile() or isDirectory() ?
Upvotes: 3
Views: 1041
Reputation: 140514
The "file" could be something like a symlink. Whether or not the distinction between a file and a symlink to a file is important depends upon your application.
Using boolean to represent "is something or something else" is a bad idea, because it's not clear what "true" or "false" mean.
Even if you remember that "true" means "is a directory", "false" logically means "is not a directory"... And so the reader is left wondering "well, I know it's not a directory, but what is it?"
And the very fact you are asking the question demonstrates this.
Consider using an enum instead:
enum Kind { DIRECTORY, FILE }
Not only is this self-documenting (you will have code saying something like "if this is a file/else if this is a directory"), it leaves the possibility of adding additional types in the future.
Upvotes: 2