Reputation: 33
I'm wondering if there is a nice way of coding something like this:
return IOTools.CreateFile(@"D:\test")
&& IOTools.CreateDir(@"D:\test_folder\")
&& IOTools.DeleteFile(@"D:\test_file_2")
&& IOTools.DeleteDir(@"D:\test_folder_2\");
I know that I can put it all in other function and there use if statements to return false after every condition, but maybe there is another way to stop program from trying to do next conditions if one is false?
Upvotes: 1
Views: 138
Reputation: 460288
&&
is already a short-circuiting operator. So it stops as soon as one condition is false
.
if x is false, y is not evaluated, because the result of the AND operation is false no matter what the value of y is. This is known as "short-circuit" evaluation.
Btw, ||
does also stop evaluation as soon as one condition is true
.
If you instead ask for a more readable way, you could use variables:
bool canCreateFile = IOTools.CreateFile(@"D:\test");
bool canCreateDir = IOTools.CreateDir(@"D:\test_folder\");
bool canDeleteFile = IOTools.DeleteFile(@"D:\test_file_2");
bool canDeleteDir = IOTools.DeleteDir(@"D:\test_folder_2\");
return canCreateFile && canCreateDir && canDeleteFile && canDeleteDir;
If code is getting too complicated i use variables to increase readability, maintainability and testability.
Upvotes: 4
Reputation: 10430
A few really important guidelines:
Hopefully that helps a bit.
More Details
An example of where editing is difficult. Lets say another programmer wants to add a new create to your program. Now the program is:
return IOTools.CreateFile(someNewFile)
&& IOTools.CreateFile(@"D:\test")
&& IOTools.CreateDir(@"D:\test_folder\")
&& IOTools.DeleteFile(@"D:\test_file_2")
&& IOTools.DeleteDir(@"D:\test_folder_2\");
But the new programmer makes a mistake and that file happens to never be created. They followed your pattern - and actually broke your code. This is a serious issue suddenly! A much better pattern would be:
var overallSuccess = false;
overallSuccess |= IOTools.CreateFile(someNewFile);
overallSuccess |= IOTools.CreateFile(@"D:\test");
overallSuccess |= IOTools.CreateDir(@"D:\test_folder\");
overallSuccess |= IOTools.DeleteFile(@"D:\test_file_2");
overallSuccess |= IOTools.DeleteDir(@"D:\test_folder_2\");
return overallSuccess;
Now all statements run and the return value represents whether or not ANY create was successful. You can change the "|=" to an "&=" to have true return if ALL statements were successful. Best of luck!
Upvotes: 0
Reputation: 8793
This is about as clean as you will get. Introducing anything else will likely add, rather than reduce, complexity.
Upvotes: 0