Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c# is this design "Correct"?

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
        }
like image 213
bevacqua Avatar asked Oct 15 '10 13:10

bevacqua


4 Answers

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.

like image 73
Ani Avatar answered Sep 22 '22 04:09

Ani


Is the first code a set of OR statements?

if ( 
       (!RunCommand(LogonAsAServiceCommand)) 
    || (!ServicesRunningOrStart()) 
    || (!ServicesStoppedOrHalt()) 
    || (!BashCommand(CreateRuntimeBashCommand)) 
    || (!ServicesStoppedOrHalt()) 
    || (!BashCommand(BootstrapDataBashCommand)) 
    || (!ServicesRunningOrStart()) 
like image 34
Mark Dickinson Avatar answered Sep 21 '22 04:09

Mark Dickinson


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....

like image 26
Preet Sangha Avatar answered Sep 18 '22 04:09

Preet Sangha


You should stick to whatever is more readable, and understandable.

Unless it is real inefficient.

like image 39
Adriaan Stander Avatar answered Sep 21 '22 04:09

Adriaan Stander