开发者

compact C# expression for multiple consecutive non-nested breaking ifs

I currently have

if A {
    //code
    return;
}
if B {
    //code
    return;
}
...

Is there a simple way to express this for a large number of conditions?

The goal in this case is validation of something that can fail in different ways, which all require different handling.

I then expect this block of code to be called again later, whe开发者_如何学编程n whatever condition has just been resolved will fail, and it will slip through the tests until it meets another condition and is rejected in a new and exciting way.

I was really just hoping for something on the level of a switch statement (in terms of simplicity and ease of use) but I guess that doesn't exist...


Possibly, but it's really hard to guide you without knowing more about the types of conditions you have and what the code in each one does... if there are similarities, you can probably find ways to abstract those out instead of repeating them (using 'switch' statements, delegates, etc). If these things are totally unrelated, it won't get any better than what you have shown - except to change latter 'if's to 'else if' and then put a single 'return' at the very end.


If your conditions are testing the same value for equality with other values, you can use the switch statement. Note that in C#, unlike C++ or Java, you can use a string as the switch value.

You can use the ?: operator but only if your "code" can be expressed as a single expression and they all return the same type. So for example,

var user = conditionA ? expressionA :
           conditionB ? expressionB :
           conditionC ? expressionC;

It would probably help most though if you say what your actual problem is. It's possible a cleaner approach would be possible through polymorphism, array/dictionary lookups, etc.


You could use class that inherit an abstract base class ConditionalAction, which could look like this:

public abstract class ConditionalAction
{
    public abstract bool Condition();
    public abstract void Action();
}

A sample class that inherits ConditionalAction:

public class SampleConditionalAction : ConditionalAction
{
    public override bool Condition()
    {
        // Condition
    }
    public override void Action()
    {
        // Code
    }
}

Sample implementation:

List<ConditionalAction> conditionalActions = new List<ConditionalAction>();
conditionalActions.Add(new SampleConditionalAction());
// Add more ConditionalActions...

foreach(ConditionalAction conditionalAction in conditionalActions)
{
    if (conditionalAction.Condition())
        conditionalAction.Action();
}

The main place you'd get stuck with this approach is if you need information for your conditions or your actions, but you can build that in by passing in parameters to your constructors of your ConditionalActions.


You can create a Dictionary<Func<bool>, Action>. The keys will be the conditions (every one of them a bool Method()) and the values will be the pieces of code to execute.

Then you can easily iterate through the keys that meet the codition and execute their values:

foreach (pair in dictionary.Where(pair => pair.Key()))
{
    pair.Value();
}


It depends what the conditionals are, the code is doing and the design of the component.

For example, if it's a configuration class that stores a load of settings then I'd have no problem with the above. Conversely if this defines or controls paths of execution in your application then that might suggest a design deficiency. Lots of conditionals or switch statements can be refactored using inheritance or dependency injection for example.

If you have a serious number of conditions and it isn't a config class I would think about your code at a design level, rather than a syntactic one.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜