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.
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 09 '19 at 22:00Action<string>
and you'd supply a simple lambda likes => StreamWriter.WriteLine(s)
to that parameter when calling the method. – David Arno Jul 10 '19 at 06:31