Thilina H
Thilina H

Reputation: 5802

How can i identify which condition failed in a if statement with multiple OR conditions?

How can i identify which condition failed in a if statement with multiple OR conditions.example as following.

if ((null == emailNotificationData || string.IsNullOrEmpty(emailNotificationData.Sender))
                        || null == emailNotificationData.ToRecipients)
  {
    LogProvider.Log(typeof(Notification), LogLevel.Error, "Error sending the email notification 'Here i want to log failed argument'");
    return;
  }

Upvotes: 1

Views: 3473

Answers (3)

Multi1209
Multi1209

Reputation: 121

You can create a validation rule to check the emailNotificationData.

public class Rule<T>
{
    public Func<T, bool> Test { get; set; }

    public string Message { get; set; }
}

Then you create a class where you define the rules for your emailNotificationData.

public class EmailNotificationValidationRules
{
    public static IEnumerable<Rule<EmailNotificationData>> Rules 
    {
        get
        {
            return new List<Rule<EmailNotificationData>>
                {
                    new Rule<EmailNotificationData> { Test = data => data != null, Message = "No email notifacation data" },
                    new Rule<EmailNotificationData> { Test = data => !string.IsNullOrEmpty(data.Sender), Message = "No sender" },
                    new Rule<EmailNotificationData> { Test = data => data.ToRecipients != null, Message = "No recipients" }
                };
        }
    }
}

Now you can check the your object with this code

        bool isValid = EmailNotificationValidationRules.Rules.All(rule => rule.Test(emailNotificationData));

        if (isValid == false)
        {
            var failedRules = EmailNotificationValidationRules.Rules.Where(rule => rule.Test(emailNotificationData) == false);
            var text2Log = failedRules.Aggregate(new StringBuilder(), (builder, rule) => builder.AppendLine(rule.Message), builder => builder.ToString());
        }

The field text2log contains only the messages of the failed rules.

Upvotes: 2

Tim Schmelter
Tim Schmelter

Reputation: 460138

Either use multiple ifs or meaningful bool variables:

bool noEmailData = emailNotificationData == null;
bool noEmailSender = string.IsNullOrEmpty(emailNotificationData.Sender);

if(noEmailData || noEmailSender)
{
    string msg = string.Format("Error sending the email notification: {0} {1}."
        , noEmailData ? "No email-data available" : ""
        , noEmailSender ? "No email-sender available" : "");
    LogProvider.Log(typeof(Notification), LogLevel.Error, msg);
}

That increases readability in general.

Upvotes: 7

Jon Skeet
Jon Skeet

Reputation: 1500785

You can't, without rechecking each condition. I'd just write that as:

if (emailNotificationData == null)
{
    // This is a helper method calling LogProvider.Log(...)
    LogEmailNotificationError("No email notification data");
    return;
}
if (string.IsNullOrEmpty(emailNotificationData.Sender))
{
    LogEmailNotificationError("No sender");
    return;
}
if (emailNotificationData.ToRecipients == null)
{
    LogEmailNotificationError("No recipients");
    return;
}

You could extract this into a ValidateAndLog extension method on your notification data type though - making it an extension method means you can handle it being null, too:

// ValidateAndLog returns true if everything is okay, false otherwise.
if (!emailNotificationData.ValidateAndLog())
{
    return;
}

That way it doesn't need to clutter up other code.

Note that there's almost never any benefit in C# to writing:

if (null == x)

... unless you're actually comparing Boolean values, the "normal" reason for preferring the constant-first comparison (catching a typo of = for ==) doesn't apply, as if (x = null) wouldn't compile anyway.

Upvotes: 11

Related Questions