简体   繁体   中英

Using else with multiple if statements C#

Is there a way to quickly check the following logic? I'm using C#.

if(a)
{
}
if(b)
{
}
if(c)
{
}
else none of the above //...? execute if all above conditions are false
{
}

This differs from using if-else in that a, b, and c can all be true at once. So I can't stack them that way. I want to check else for a, b, and c are all false without writing if(!a && !b && !c) . This is because the code can get quite messy when the if conditions become more complex. It requires rewriting a lot of code. Is this possible?

Well it's not pretty "clean", but I'd do

bool noneAreTrue = true;
if(a)
{
    noneAreTrue = false;
}
if(b)
{
    noneAreTrue = false;
}
if(c)
{
    noneAreTrue = false;
}
if(noneAreTrue)
{
    //execute if all above conditions are false
}

Also, if your conditions are really pretty big, I recommend the rule G28 (Encapsulate Conditionals) from the book Clean Code from Robert C. Martin

It is pretty verbose , but can be easier to read in some instances :

public void YourMethod()
{
    if(SomeComplexLogic())
    {
    }
    if(SomeMoreLogic())
    {
    }
    if(EvenMoreComplexLogic())
    {
    }
    if(NoComplexLogicApply())
    {
    }
}

private bool SomeComplexLogic(){
    return stuff;
}

private bool EvenMoreComplexLogic(){
    return moreStuff;
}

private bool EvenMoreComplexLogic(){
    return evenMoreStuff;
}

private bool NoComplexLogicApply(){
    return SomeComplexLogic() && EvenMoreComplexLogic() && EvenMoreComplexLogic();
}

How about combine the concepts of Strategies and Specifications

var strategies = _availableStrategies.All(x => x.IsSatisfiedBy(value));
foreach (var strategy in strategies)
{
    strategy.Execute(context);
}
if (!strategies.Any()) {
    // run a different strategy
}

Rather than encapsulate some complex condition in a method that you will only ever call once or twice, I would just keep in a variable. This is also more readable than using some marker boolean as other answers suggest.

A contrived example,

bool isBlue = sky.Color == Colors.Blue;
bool containsOxygen = sky.Atoms.Contains("oxygen") && sky.Bonds.Type == Bond.Double;
bool canRain = sky.Abilities.Contains("rain");
if(isBlue)
{
}
if(containsOxygen)
{
}
if(canRain)
{
}
if(!isBlue && !containsOxygen && !canRain)
{
}

Now we have abstracted what might otherwise be complex conditions into readable English!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM