简体   繁体   中英

How to avoid this nested if statement?

I want to check if one file exists in two different paths. If the first one doesn't, check the second.

filepath1 = "/path1/file.txt"
filepath2 = "/path2/file.txt"
file_descriptor = open(filepath1)

if ( !file_descriptor.open() )
{
    print("file 1 did not work");
   
    //try file 2
    file_descriptor = open(filepath2);
    if( !file_descriptor.open() )
    {
        print("could not open file 2. exiting.");
        return false;
    }
}

//we get here and file_descriptor should point to a valid file
read_file(file_descriptor);
return true;

How can I avoid the nested if statement? Preferably, I'd like to not nest the if statements for readability. The problem here is that if the first one does work, I don't want it to check the second if statement.

I thought about using:

  • goto (I want to avoid this)
  • boolean to check if one works (but now I'm introducing extra variables)

if you don't care about which file is open you can do

filepath1 = "/path1/file.txt"
filepath2 = "/path2/file.txt"

if (!(file_descriptor = open(filepath1)).open() &&
    !(file_descriptor = open(filepath2)).open())
{
    print("could not open file 1 nor 2. exiting.");
    return false;
}
...

else if you really want only one if you can do

filepath1 = "/path1/file.txt"
filepath2 = "/path2/file.txt"

if (!(file_descriptor = open(filepath1)).open() &&
    (print("file 1 did not work"),
     !(file_descriptor = open(filepath2)).open()))
{
    print("could not open file 2. exiting.");
    return false;
}
...

but this makes the code less clear than with the two if s

PS do not think about using goto

I guess this pattern is pretty general: you can try as many paths as you wish:

auto filepath1 = "/path1/file.txt";
auto filepath2 = "/path2/file.txt";
// We assume file_descriptor has been declared earlier

for (const auto fpath: {filepath1, filepath2})
{
   file_descriptor = open(fpath)
   if (file_descriptor.open()) 
      break;
   else
      printf("file %s did not work\n", fpath);  
}
if (!file_descriptor.open()) return false;  // or throw

read_file(file_descriptor);
return true;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM