Наиболее эффективный и элегантный способ проверки параметров с использованием условий if - PullRequest
0 голосов
/ 13 сентября 2018

У меня есть 3 параметра для проверки с некоторыми условиями.

В качестве примера мой код выглядит следующим образом:

    public static string checkIfConnditions(string msg, int score, int age)
    {
        var response = "";

        if (msg == "hello" && score >= 20 && age <= 25)
        {
            response = "All para success";
        }
        if (msg != "hello" && score >= 20 && age <= 25)
        {
            response = "Unmatching message";
        }
        if (msg == "hello" && score < 20 && age <= 25)
        {
            response = "Score not satisfied";
        }
        if (msg == "hello" && score >= 20 && age > 25)
        {
            response = "Age not satisfied";
        }
        if (msg != "hello" && score < 20 && age <= 25)
        {
            response = "Unmatiching message & Score not satisfied ";
        }
        if (msg != "hello" && score >= 20 && age > 25)
        {
            response = "Unmatiching message & Age not satisfied";
        }
        if (msg == "hello" && score < 20 && age > 25)
        {
            response = "Age & Score not satisfied";
        }
        if (msg != "hello" && score < 20 && age > 25)
        {
            response = "All parameter unsatisfied";
        }
        return response;
    }}

Там есть 3 параметра, и 8 вероятностей могут произойти на основе его значений.Здесь я проверяю те, как выше код.Но это выглядит ужасно, и я думаю, что это не лучший способ сделать это.какой самый эффективный и элегантный способ сделать это

Ответы [ 6 ]

0 голосов
/ 13 сентября 2018

Я бы связал результаты:

public string checkIfConnditions(string msg, int score, int age)
{
    List<String> msgList = List<String>();    
    if (msg != "hello")
        msgList.add("Message");

    if (score < 20)
        msgList.add("Score");

    if (age > 25)
        msgList.add("Age");

    var response = "All para success"
    for(int i=0;i<msgList.Count;i++)
    {
         if(i=0) 
             response = msgList[i] 
         else 
             response += " & "+ msgList[i] 

         if(i==msgList.Count-1)
             response += " not satisfied"
    }

    return response;
0 голосов
/ 13 сентября 2018
 Sometimes these long "if's" can get a little messy.
        public string checkIfConnditions(string msg, int score, int age)
        {
            string response = string.Empty;
            if (msg == "hello")
            {
                if (score > 20 && age < 25)
                    response = "All para success";
                else if (score < 20 && age < 25)
                    response = "Score not satisfied";
                else if (score > 20 && age > 25)
                    response = "Age not satisfied";
                else if ( score < 20 && age > 25)     // Corrected this line
                    response = "Age & Score not satisfied";
            }
            else
            {
                if (score < 20 && age < 25)
                    response = "Unmatiching message & Score not satisfied ";
                else if (score > 20 && age > 25)
                    response = "Unmatiching message & Age not satisfied";
                else if (score > 20 && age < 25)
                    response = "Unmatching message";
                else if (score < 20 && age > 25)
                    response = "All parameter unsatisfied";
            }
            return response;
        }
0 голосов
/ 13 сентября 2018
            List<String> Errors = new List<String>();
            int chk = 3;
            if ( msg != "hello" )
            {
                Errors.Add( "Unmatching message" );
            }
            if ( score < 20 )
            {
                Errors.Add( "Score not satisfied" );
            }
            if ( age > 25 )
            {
                Errors.Add( "Age not satisfied" );
            }

            if ( Errors.Count == 0 )
            {
                return "All para success";
            }
            else if ( Errors.Count == 3)
            {
                return "All parameter unsatisfied";
            }
            else
            {
                return String.Join( " & ", Errors );
            }

** Код отредактирован, потому что я неправильно набрал String.Join как String.Format **

, или вы также можете использовать байт для этого, если вы хотите, чтобы ответы по каждому случаю

            int flag = 0x0;
            if ( msg == "hello" )
            {
                flag |= 0x1;
            }
            if ( score > 20 )
            {
                flag |= 0x2;
            }
            if ( age < 25 )
            {
                flag |= 0x4;
            }
            switch ( flag )
            {
                case 0x7:
                    response = "All para success";
                    break;
                case 0x6:
                    response = "Unmatching message";
                    break;
                case 0x5:
                    response = "Score not satisfied";
                    break;
                case 0x4:
                    response = "Unmatiching message & Age not satisfied";
                    break;
                case 0x3:
                    response = "Score not satisfied";
                    break;
                case 0x2:
                    response = "Unmatiching message & Score not satisfied ";
                    break;
                case 0x1:
                    response = "Score not satisfied & Age not satisfied";
                    break;
                default:
                    response = "All parameter unsatisfied";
                    break;


            }
0 голосов
/ 13 сентября 2018

Одним из возможных способов может быть создание словаря, который содержит вашу таблицу истинности и соответствующий ответ, например:

private readonly Dictionary<(bool isMsgValid, bool isScoreValid, bool isAgeValid), string> _responses 
    = new Dictionary<(bool, bool, bool), string>()
{
    [(true, true, true)] = "All para success",
    [(false, false, false)] = "All parameter unsatisfied",
    [(false, true, true)] = "Unmatching message",
    [(true, false, true)] = "Score not satisfied",
    [(true, true, false)] = "Age not satisfied",
    [(false, false, true)] = "Unmatiching message & Score not satisfied",
    [(false, true, false)] = "Unmatiching message & Age not satisfied",
    [(true, false, false)] = "Age & Score not satisfied"
};

public string checkIfConnditions(string msg, int score, int age)
    => _responses[(msg == "hello", score > 20, age < 25)];

Вам решать, какой вариант более элегантный, это только один изВозможные решения1012 *

Вот пример, который я использовал для тестирования:

public static class Program
{
    private static readonly Dictionary<(bool isMsgValid, bool isScoreValid, bool isAgeValid), string> _responses 
        = new Dictionary<(bool, bool, bool), string>()
    {
        [(true, true, true)] = "All para success",
        [(false, false, false)] = "All parameter unsatisfied",
        [(false, true, true)] = "Unmatching message",
        [(true, false, true)] = "Score not satisfied",
        [(true, true, false)] = "Age not satisfied",
        [(false, false, true)] = "Unmatiching message & Score not satisfied",
        [(false, true, false)] = "Unmatiching message & Age not satisfied",
        [(true, false, false)] = "Age & Score not satisfied"
    };

    public static string checkIfConnditions(string msg, int score, int age)
        => _responses[(msg == "hello", score > 20, age < 25)];

    public static void Main(string[] args)
    {
        Console.WriteLine(checkIfConnditions("hello", 45, 20));
        Console.WriteLine(checkIfConnditions("hello", 45, 30));
        Console.WriteLine(checkIfConnditions("hello", 10, 20));
        Console.WriteLine(checkIfConnditions("hello", 10, 30));
        Console.WriteLine(checkIfConnditions("goodbye", 45, 20));
        Console.WriteLine(checkIfConnditions("goodbye", 10, 30));
        Console.WriteLine(checkIfConnditions("goodbye", 45, 20));
        Console.WriteLine(checkIfConnditions("goodbye", 10, 30));
    }
}

Обратите внимание, что _responses и checkIfConnditions должны быть статическими в этом случае.

0 голосов
/ 13 сентября 2018
    private const string MESSAGE = "hello";
    private const int SCORE = 20;
    private const int AGE = 25;
    public string checkIfConnditions(string msg, int score, int age)
    {
        if (msg == MESSAGE)
        {
            if (score > SCORE)
            {
                return age < AGE ? "All para success" : "Age not satisfied";
            }
            else
            {
                return age < AGE ? "Score not satisfied" : "Age & Score not satisfied";
            }

        }
        else
        {
            if (score > SCORE)
            {
                return age < AGE ? "Unmatching message" : "Unmatiching message & Age not satisfied";
            }
            else
            {
                return age < AGE ? "Unmatiching message & Score not satisfied " : "All parameter unsatisfied";
            }
        }            
    }
0 голосов
/ 13 сентября 2018

как насчет группировки сначала так:

public string checkIfConnditions(string msg, int score, int age)
{
   var response = "";

   if (msg == "hello") {
       response = score > 20 ? 
        age > 25 ? "Age not satisfied" : "All para success"
        : age < 25 ? "Score not satisfied" : "Age & Score not satisfied";       
   } else {
        if  (score > 20)
        {
            response = age < 25 ? "Unmatching message" : "Unmatiching message & Age not satisfied" ;    

        } else {

            response = age < 25 ? "Unmatiching message & Score not satisfied " : "All parameter unsatisfied" ;          
        }   
   }    
   return response;
 }

также нужно отметить условие, если оно равно. например

if (msg == "hello" && score > 20 && age < 25)
{
    response = "All para success";
}

//and ...
if (msg == "hello" && score < 20 && age < 25)
{
    response = "Score not satisfied";
}
// what if score == 20 ?

с if else заявлением или The conditional operator (?:) мы можем избежать этого

Обновление

if(msg == "hello")
{
    if(score < 20)
    {
        response = age > 25 ? "Age & Score not satisfied" : "Score not satisfied";
    } else {
        response = age > 25 ? "Age not satisfied" : "All para success";
    }
} else {
    if(score < 20)
    {
        response = age > 25 ? "All parameter unsatisfied" : "Unmatiching message & Score not satisfied ";
    } else {
        response = age > 25 ? "Unmatiching message & Age not satisfied" : "Unmatching message";     
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...