avoid If/Else statements

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • dmjpro
    Top Contributor
    • Jan 2007
    • 2476

    #16
    Originally posted by avinash jain
    Hi to all
    Could any one tell me how to avoid if/else statements uisng inheritance..
    The Picture is not clear to me.
    Will you send some code and then tell me what's your problem with that code.

    Kind regards,
    Dmjpro.

    Comment

    • avinash jain
      New Member
      • Aug 2007
      • 12

      #17
      Originally posted by RRick
      If you're looking for an example, then let's make up a simple one where you enter a value at the keyboard in response to: "Specify an algorithm".

      You want to take the response from cin, probably put into a string and create an algor object. How do we create the correct algorithm object? The only way I know of, is to create an if ... else if ... conditional structure.
      Code:
      if ( response == "min")
      {  //  Make min object }
      else if ( response == "max")
      { blah blah blah }
      
      // Keep extending the structure until all cases are handled
      One technique is to take this code and put it into a static builder that returns a base pointer to the algor object.
      Code:
      AlgorBase * algor = Algor::Builder( response);
      While this hides the details of creating the algor object from the application, you'll still need the cascading "if" structure.
      *************** *************** *************** *************** *************** *************** **Thank you for replying ...
      I have have got a link..
      http://www.parashift.c om/c++-faq-lite/virtual-functions.html. ...
      in the section[20.6]..
      My problem is of the same type .. could please help me without using vectors.or templates..

      Comment

      • Darryl
        New Member
        • May 2007
        • 86

        #18
        There are various ways to avoid if and if else, but they dependent on what you are trying to do, for example starting with the example above:
        Code:
        if ( response == "min")
        {  //  Make min object }
        else if ( response == "max")
        { blah blah blah }
        I could do something like
        Code:
        ( (response == "min") && MakeMinObject() ) || ( (response == "max") && MakeMaxObject() )
        or let's suppose I am just trying to assign min or max value depending on users response, I could use the fact that true converts to int 1 and false to int 0 and do

        Code:
        value = (response == "min")*minvalue + (response == "max")*maxvalue;

        Comment

        • RRick
          Recognized Expert Contributor
          • Feb 2007
          • 463

          #19
          Avinash,

          I looked at the example on the web site and it's pretty good in describing how to implement inheritence. It also shows the down side of C style if-else blocks that do the same thing. Don't get hung up on the vector and template. They define a container for looping through the vehicles and nothing more. A simpler container example would be an array of pointers to vechicles. In this case you use pointers the to access the vehicles. Everything else stays the same.

          The trick with inheritence is that when done correctly, you don't need the if-else-... blocks of code. When I see a discussion of heritence and if-else blocks it is usually when someone is describing how C++ can replace and improve C structures.

          Comment

          • avinash jain
            New Member
            • Aug 2007
            • 12

            #20
            Originally posted by RRick
            Avinash,

            I looked at the example on the web site and it's pretty good in describing how to implement inheritence. It also shows the down side of C style if-else blocks that do the same thing. Don't get hung up on the vector and template. They define a container for looping through the vehicles and nothing more. A simpler container example would be an array of pointers to vechicles. In this case you use pointers the to access the vehicles. Everything else stays the same.

            The trick with inheritence is that when done correctly, you don't need the if-else-... blocks of code. When I see a discussion of heritence and if-else blocks it is usually when someone is describing how C++ can replace and improve C structures.
            #include<iostre am>

            using namespace std;
            class Zaman
            {
            public:
            virtual void Sing()=0;
            };

            class LirilGirl:publi c Zaman
            {
            //virtual keyword is optional here
            /*virtual*/
            public:
            void Sing()
            {
            std::cout<<"La. .lalalala....La aa..Laa..laaa.l aaa";
            }
            };

            class NirmaGirl:publi c Zaman{

            public:
            void Sing()
            {
            std::cout<<"Nir ma...Nirma.iske jhaag ne jaadu kar diya..";
            }
            };

            int main()
            {
            if(size == medium)
            lirilgirl;
            else
            nirmagirl;
            return 0;
            }


            see in the above example ..its good to added..cases..a t the end..
            but in case in the market we get many girls.. then we cant keep those many if/else statements...fo r that we need to avoid the if/else statements in my code...sometime s we may forgot to added the cases.. then we will wasting time ...
            I hope you understood my problem..

            Comment

            • kreagan
              New Member
              • Aug 2007
              • 153

              #21
              Originally posted by avinash jain
              #include<iostre am>

              using namespace std;
              class Zaman
              {
              public:
              virtual void Sing()=0;
              };

              class LirilGirl:publi c Zaman
              {
              //virtual keyword is optional here
              /*virtual*/
              public:
              void Sing()
              {
              std::cout<<"La. .lalalala....La aa..Laa..laaa.l aaa";
              }
              };

              class NirmaGirl:publi c Zaman{

              public:
              void Sing()
              {
              std::cout<<"Nir ma...Nirma.iske jhaag ne jaadu kar diya..";
              }
              };

              int main()
              {
              if(size == medium)
              lirilgirl;
              else
              nirmagirl;
              return 0;
              }


              see in the above example ..its good to added..cases..a t the end..
              but in case in the market we get many girls.. then we cant keep those many if/else statements...fo r that we need to avoid the if/else statements in my code...sometime s we may forgot to added the cases.. then we will wasting time ...
              I hope you understood my problem..
              [CODE=c]
              char girlarray[] = {"lirilgirl" , nirmagirl } //array of strings

              [/CODE]

              Comment

              • kreagan
                New Member
                • Aug 2007
                • 153

                #22
                Originally posted by avinash jain
                #include<iostre am>

                using namespace std;
                class Zaman
                {
                public:
                virtual void Sing()=0;
                };

                class LirilGirl:publi c Zaman
                {
                //virtual keyword is optional here
                /*virtual*/
                public:
                void Sing()
                {
                std::cout<<"La. .lalalala....La aa..Laa..laaa.l aaa";
                }
                };

                class NirmaGirl:publi c Zaman{

                public:
                void Sing()
                {
                std::cout<<"Nir ma...Nirma.iske jhaag ne jaadu kar diya..";
                }
                };

                int main()
                {
                if(size == medium)
                lirilgirl;
                else
                nirmagirl;
                return 0;
                }


                see in the above example ..its good to added..cases..a t the end..
                but in case in the market we get many girls.. then we cant keep those many if/else statements...fo r that we need to avoid the if/else statements in my code...sometime s we may forgot to added the cases.. then we will wasting time ...
                I hope you understood my problem..
                One way is to use a function pointer. You still cannot remove all if statements/switch statements ... but this might aid in better organizations. For more reading <a href = "http://www.newty.de/fpt/intro.html#what ">

                [CODE=c]
                char girlarray[] = {"lirilgirl" , "nirmagirl" } //array of strings
                int girlweight[] = { MEDIUM, SMALL } //identification for the girl.
                char girlfunction[] = { lirilFunction, nirmaFunction } //function pointers for each girl.

                //somewhere in code
                for ( int i = 0; i < array_size; i++ ){
                if ( size == girlweight[i] ){
                instantiateGirl ( &girlfunctio n[i] );
                break;
                }
                }

                //somewhere in code
                void instantiateGirl ( void (*pt2Func)( ) )
                {
                pt2Func( ); // call using function pointer
                }
                }
                [/CODE]

                Along with function pointers, for large amounts of information or dynamic information, look into databases and config files ( .ini files). This will help with maintance of your code.

                If you don't want a for loop to go through the whole list of sizes - lets say there is a billion of them. You can use searching alorithms to find the index of the array, shortening your time.

                PS. treat this as psuedo code. There may be syntax errors. Refer to document about function pointers for correct information.

                Good luck.

                Comment

                Working...