I currently have the following
if (!RunCommand(LogonAsAServiceCommand))
return;
if (!ServicesRunningOrStart())
return;
if (!ServicesStoppedOrHalt())
return;
if (!BashCommand(CreateRuntimeBashCommand))
return;
if (!ServicesStoppedOrHalt())
return;
if (!BashCommand(BootstrapDataBashCommand))
return;
if (!ServicesRunningOrStart())
return;
would it be cleaner to do this? is it safe?
if (
(RunCommand(LogonAsAServiceCommand))
&& (ServicesRunningOrStart())
&& (ServicesStoppedOrHalt())
&& (BashCommand(CreateRuntimeBashCommand))
&& (ServicesStoppedOrHalt())
&& (BashCommand(BootstrapDataBashCommand))
&& (ServicesRunningOrStart())
)
{
// code after "return statements" here
}
When I look at the first approach, my first thought is that the reason the code has been written in that way is that the operations involved probably have side-effects. From the names of the methods, I assume they do? If so, I would definitely go with the first approach and not the second; I think readers of your code would find it very confusing to see a short-circuiting &&
expression being used to conditionally execute side-effects.
If there are no side-effects, either will do; they are both perfectly readable. If you find that there are several more conditions or the conditions themselves vary in different scenarios, you could try something like:
Func<bool>[] conditions = ...
if(conditions.Any(condn => condn()))
{
...
}
I wouldn't really go with such an approach in your case, however.
Is the first code a set of OR statements?
if (
(!RunCommand(LogonAsAServiceCommand))
|| (!ServicesRunningOrStart())
|| (!ServicesStoppedOrHalt())
|| (!BashCommand(CreateRuntimeBashCommand))
|| (!ServicesStoppedOrHalt())
|| (!BashCommand(BootstrapDataBashCommand))
|| (!ServicesRunningOrStart())
Either is fine. However from a style perspective I'd suggest that since this is a series of comands you could use a List<Action>
to hold these and make the function data driven.
(new Action[] { func1, func2, .... }).ToList().ForEach(a => a());
Of course since the functions have differing signatures you may have to do multiple ones...
again it's a style matter....
You should stick to whatever is more readable, and understandable.
Unless it is real inefficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With