0

I have several areas in a program where I am doing the following check on the same two booleans, but each spot has different text being written to a file via Stream Writer based on the value of the booleans.

Example

if (bool1 && bool2)
{
  StreamWriter.WriteLine("Stuff to the file");
  StreamWriter.WriteLine("Stuff 2 to the file");
  StreamWriter.WriteLine("Stuff 3 to the file");
}
else if (bool1) 
{
  StreamWriter.WriteLine("Stuff 4 to the file");
  StreamWriter.WriteLine("Stuff 5 to the file");
  StreamWriter.WriteLine("Stuff 6 to the file");
} 
else if (bool2) 
{
  StreamWriter.WriteLine("Stuff 7 to the file");
  StreamWriter.WriteLine("Stuff 8 to the file");
  StreamWriter.WriteLine("Stuff 9 to the file");
}

The thought process is, if both Booleans are true, write certain text to the file. Else if only bool1 is true, then write this bool1 specific text. Else if only bool2 is true, then write this bool2 specific text.

There are at least 3 places in my program where I'm doing these comparisons, with the WriteLine text based on the Boolean values being different in each place.

Is there a better way to do this kind of comparison logic? Such that I wouldn't need to be checking the same booleans over and over to write the various texts to the file.

I've considered writing a method that takes in 3 values representing what should be written to the file based on the Boolean comparisons. I am struggling however to understand how I would pass WriteLine calls as parameters to a method.

  • No, there's no "standard." Try this: Avoid Else, Return Early. – Robert Harvey Jul 9 at 19:43
  • @RobertHarvey Thanks, in my specific use case, I don't want to return from the method as much as I want to write different text to the file based on the boolean value. I've updated my question to try and add more details. – Godwin Jul 9 at 20:10
  • 2
    You can covert this to a switch. You have three cases: Both, JustOne and JustTwo. Define an enum for these cases and determine the case upfront. Then switch on it. – Martin Maat Jul 9 at 20:14
  • You could do it via a method or an object as you intended (you can pass in an Action (lambda) for each case), but it would be of limited benefit - you'd pretty much get the same construct, only in a different syntax. You would likely capture some of the decision-making logic, and communicate to your future self and other developers that 3 actions need to be provided - and maybe that's all you need. But if the problem is that you have cascading changes and coupled code (you're always making changes in several places/files), this approach doesn't solve that. – Filip Milovanović Jul 9 at 22:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.