Most effective and elegant way to check parameters using if conditons

refactoring if statements
replace multiple if statements in java
java 8 multiple if conditions
too many if statements
javascript if statement multiple conditions
javascript multiple if statements in a function
clean code if statements
how to reduce if statements

I have 3 parameters to check with some conditions.

As an example my code as follows,

    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;
    }}

There have 3 parameters and 8 probability can happen based on its values. Here I check those as above code. But it looks ugly and I think it's not the best way to do this. what is most efficient and elegant way to do this


what about grouping it first like so:

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;
 }

also you need to note condition if it is equal. for example

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 ?

with if else statement or The conditional operator (?:) we can avoid that

Update

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";     
    }
}

Elegant ways to handle if(if else) else, If there would be [C++] tag, I'd wrote if statement with declaration of contents in its condition part non-orthogonal (see this answer for good reasons for writing orthogonally). When testing, the general rule should be to test exceptions, not the normal case Whatever(Arguments) { if(!FileExists(file)) goto notexists; contents  +1 Strongly agree, whichever is the most compact way to check that conditions we shouldn't forget the domain. – Adriano Repetti Apr 9 '13 at 14:48 +1 here too.


            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 );
            }

** Code edited because I mis-typed String.Join as String.Format **

or you can also use byte for this if you want to make case by case answers

            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;


            }

5 Tips to Write Better Conditionals in JavaScript ― Scotch.io, Use Default Function Parameters and Destructuring; 4. function test(fruit) { // extract conditions to array const redFruits = ['apple', 'strawberry', 'cherry', This coding style is good especially when you have long if statement (imagine you need to scroll to the Look at condition 2 below to see how we do it: If you use bash for scripting you will undoubtedly have to use conditions a lot, for example for an if … then construct or a while loop. The syntax of these conditions can seem a bit daunting to learn and use. This tutorial aims to help the reader understanding conditions in bash, and provides a …


 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;
        }

7.2. More advanced if usage, This is the construct to use to take one course of action if the if commands test true, More input> else echo "How come the lady hasn't got a drink yet? the else statement can hold any UNIX-style command that returns an exit status. it is frequently more elegant to put the values for the variables on the command line​. Example 1. Using IF & AND function in Excel. Suppose, you have a table with the results of two exam scores. The first score, stored in column C, must be equal to or greater than 20. The second score, listed in column D, must be equal to or exceed 30.


One possible way could be to create dictionary, which contains your truth table and corresponding response, for example:

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)];

It's up to you to decide which variant is more elegant, this is just one of the possible solution.

Note, that here's using C# 7.0 features, ValueTuple at the dictionary keys, and expression bodied method checkIfConnditions.

EDIT

Here is the example, which I have been used for testing:

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));
    }
}

Note, that _responses and checkIfConnditions must be static in that case.

Code Smells: If Statements, Overuse or poor use of if statements is a code smell. Here I have to run all the tests again to check my hypothesis is correct (they pass, which is good). I still don't like how many parameters this method has, but we'll look  Le Corbusier was one of the greatest architects of the 20th Century. He intuitively understood how to reduce everything to its simplest and most elegant form without ever sacrificing what mattered most: the purpose of each creation and how people interact with the space around them. Data visualization is a lot like architecture.


I would concatenate the results:

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;

More advanced if usage, This is the construct to use to take one course of action if the if commands test true, More input> else echo "How come the lady hasn't got a drink yet? the else statement can hold any UNIX-style command that returns an exit status. it is frequently more elegant to put the values for the variables on the command line​. Answers Include Comments Get RSS Feed. This answer has been deleted. This answer has been undeleted. Nov 05, 2010 at 07:32 AM. select count( * ) from dbtab up to 1 rows where field = value. Seems reasonable to me.. Alert Moderator. You already have an active moderator alert for this content. Insert link Remove link.


5. Conditionals, Programs get really interesting when we can test conditions and change the For example, the operator == tests if two values are equal. In a Truth Table, we sometimes use T and F as shorthand for the two Boolean values: here is the truth table describing or: In general, it is a good idea to avoid them when we can. A class or seminar on active listening is one of the most effective ways to improve your listening skills, and by proxy, your communication skills as well. Feedback You should be able to convey your information in such a way that your targets can offer feedback or criticism on your information.


[PDF] Beyond IF THEN ELSE: Techniques for Conditional , The first and most common way to use the SELECT statement is to specify an In certain situations, these functions can produce a much more compact and elegant alternative to. IF… ifc(num_kids=0,'no',put(num_kids,best.)), Each of the arguments passed to IFC or IFN are evaluated before the logical test is performed. A rectal temperature is generally considered to be the most accurate, and the standard for monitoring the core body temperature, but it is generally not recommended for use in patients, due to the risk of rectal perforation and tears with this method.


Nuclear Reactor Thermal Hydraulics and Other Applications, The good agreement of the test calculations with similar calculations of earlier versions applied to data, initial and boundary conditions, resulting parameters from integration). a coolant channel if changing between single-phase and two​-phase conditions and vice versa can be circumvented in a very elegant way in the  Using categories and tags will give you a lot of the same benefits, and they’re both taxonomies used in similar ways in the WordPress dashboard. Sometimes it’s difficult to decide if a certain topic should be a tag or a category — and many blogs will even use them in the same way.