avoid If/Else statements

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • avinash jain
    New Member
    • Aug 2007
    • 12

    avoid If/Else statements

    Hi
    Could any one help me ... I need to avoid If / else statements in my code. I have searched but I could not any simple solution for that.
    Its said to use vectors.But I ddont want to use those vectors. or templates.
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    Originally posted by avinash jain
    I need to avoid If / else statements in my code.
    All I can think of to say is why?

    Removing the single most useful and most used control structure does not sound like a receipe for a well formed program to me.

    Comment

    • JosAH
      Recognized Expert MVP
      • Mar 2007
      • 11453

      #3
      Originally posted by Banfa
      All I can think of to say is why?

      Removing the single most useful and most used control structure does not sound like a receipe for a well formed program to me.
      We don't need no steenkin' if-else statements; we can do well without them as
      long as we've got the famous ?: ternary operator; it works better for obfuscation too.

      kind regards,

      Jos ;-)

      Comment

      • kreagan
        New Member
        • Aug 2007
        • 153

        #4
        Originally posted by avinash jain
        Hi
        Could any one help me ... I need to avoid If / else statements in my code. I have searched but I could not any simple solution for that.
        Its said to use vectors.But I ddont want to use those vectors. or templates.
        I agree with Banfa, why? At any rate, you can use a switch statement which is easier to read and actually more effective than if else statement. However, you can only use switch cases with primative types (int, double, char).

        I guess you can trick a while loop or for to be an if statement. However, anyone reading your code would want to rip their eyes out.

        Comment

        • weaknessforcats
          Recognized Expert Expert
          • Mar 2007
          • 9214

          #5
          Originally posted by kreagan
          However, you can only use switch cases with primative types (int, double, char).
          Actually a switch can only be used with integer types: char, short, int, long.

          It is a form of goto-depending-on that was popular in 1972.

          switch is replaced in C++ by function oveloading or by design patterns like State.

          Comment

          • Banfa
            Recognized Expert Expert
            • Feb 2006
            • 9067

            #6
            Originally posted by weaknessforcats
            switch is replaced in C++ by function oveloading or by design patterns like State.
            That is a bit of a blanket statement that I think is rather over stating the point. I suspect that even in C++ there are situations where using a switch statement is sensible.

            Comment

            • weaknessforcats
              Recognized Expert Expert
              • Mar 2007
              • 9214

              #7
              Originally posted by Banfa
              I suspect that even in C++ there are situations where using a switch statement is sensible.
              Nope.

              A switch has cases. Each case usually has different logic. C++ uses function oveloading to address this. C uses one function (since it can't overload) and a second argument to tell the funciton what to do (the case).

              Generally, a function should perform without being steered by the programmer. Programmer-in-control is structured code.

              Case in point is printf(). This function cannot display a struct Date unless the printf() switch in the printf() code is modified. That would require a change in the Universe. By using a different function, then there's no problem. You just have a lot of display functions with different argument types.

              When you need more than one display function with the same argument type you use a namespace, or perhaps, it becomes part of a class. There should no be a giant switch somewhere that says how to display all things.

              Comment

              • Banfa
                Recognized Expert Expert
                • Feb 2006
                • 9067

                #8
                Originally posted by weaknessforcats
                A switch has cases. Each case usually has different logic. C++ uses function oveloading to address this. C uses one function (since it can't overload) and a second argument to tell the funciton what to do (the case).
                Function overloading only works if there are input parameters to the function to allow them to be distiunguished. What about in the case that there are no input paramaters, for instance any where that you are receiving raw data (keyboard input, UART input, socket etc). You will be receiving raw data (bytes) and depending on what you have received you will need to be making some sort of decision on what to do.

                Is there really a way to approach this using overlaods and classes that doesn't require any decision making before you can get to the point of creating classes or calling overloaded functions?

                Comment

                • RRick
                  Recognized Expert Contributor
                  • Feb 2007
                  • 463

                  #9
                  One test to see how OO your C++ code is, is to look for switch and nested if ... else if ...else if ... etc. statements. Like W4cats said, these statements are areas which you can usually convert to the OO paradigm.

                  The one place where these switching statements are necessary is when you deal with non-OO data (like from a keyboard). In this case, you use the switching statements to create the objects that handle/process the data. Once you have the object created, the virtual methods are used instead of the switching statements.

                  Comment

                  • Nkhosinathie
                    New Member
                    • May 2007
                    • 91

                    #10
                    Originally posted by RRick
                    One test to see how OO your C++ code is, is to look for switch and nested if ... else if ...else if ... etc. statements. Like W4cats said, these statements are areas which you can usually convert to the OO paradigm.

                    The one place where these switching statements are necessary is when you deal with non-OO data (like from a keyboard). In this case, you use the switching statements to create the objects that handle/process the data. Once you have the object created, the virtual methods are used instead of the switching statements.
                    i suppose it is better to see a part of your code so that we can make conclusion
                    which selection structure you can use.

                    thanks;

                    Comment

                    • RRick
                      Recognized Expert Contributor
                      • Feb 2007
                      • 463

                      #11
                      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.

                      Comment

                      • Banfa
                        Recognized Expert Expert
                        • Feb 2006
                        • 9067

                        #12
                        Originally posted by RRick
                        One test to see how OO your C++ code is, is to look for switch and nested if ... else if ...else if ... etc. statements. Like W4cats said, these statements are areas which you can usually convert to the OO paradigm.

                        The one place where these switching statements are necessary is when you deal with non-OO data (like from a keyboard). In this case, you use the switching statements to create the objects that handle/process the data. Once you have the object created, the virtual methods are used instead of the switching statements.
                        I can see the logic of this and there is only 1 problem...

                        The message class in the project I have been working on for the past year should actually be the base (possibly abstract) class of a set of specific message classes which handle the actual data, rather than the current class that has a whole load of methods for passing raw data into and out of specific message locations.

                        Hmmm, now to just adjust the project plan to give me time to implement this new structure in the 2 programs that use it.

                        Comment

                        • weaknessforcats
                          Recognized Expert Expert
                          • Mar 2007
                          • 9214

                          #13
                          Originally posted by Banfa
                          The message class in the project I have been working on for the past year should actually be the base (possibly abstract) class of a set of specific message classes which handle the actual data, rather than the current class that has a whole load of methods for passing raw data into and out of specific message locations.

                          Hmmm, now to just adjust the project plan to give me time to implement this new structure in the 2 programs that use it.
                          Build a parallel code set. That is, create your ABC message class and declare the class interface methods. These should be public and non-virtual.

                          These public non-virtual method should call private methods that are virtual. It is these private methods that are overriden in the derived classes. For now, they should have an empty definition. That is, just a pair of braces. These private methods are now hooks.

                          Next, derive a single class. Give it a private virtual method that overrides the base class private virtual method. Code the processing of the message for this class. Probably, it's one of the cases in your switch statement.

                          Next, go to a location where you call your current message class method and remove that call and replace it and create a derived class object.

                          Do this with a CreateMessageXY Z() function. This function creates the object of Message Class XYZ on the heap and returns a handle to a base class object(not a pointer).

                          There is a handle template all set to go in the Handle Class article in the C/C++ Articles forum. You can copy it out and just use it.

                          Use this handle to call the base class method. The base class method calls the base class private virtual method, which has been overriden by the derived class private virtual method and since this is a derived object, you are really calling the private method in the derived class for the derived object you just created.

                          This technique is a design pattern called the Template Method. See Design Patterns by Erich Gamma, et al. Addison-Wesley 1994 page 325.

                          The handle will take care of calling the destructor at the correct time shoudl you have several handles to the same derived class message object.

                          If you do it this way, you can ease in the new hierarchy gradually and verify the application still functions each step of the way. At some point you will remove the last call to your old message objject and you can then retire the class. This may allow you to not have to adjust your project schedule in any way.

                          Comment

                          • avinash jain
                            New Member
                            • Aug 2007
                            • 12

                            #14
                            I need an example..so that I could try on my PC..
                            I came to know that in C++. It could be avoided by using inheritance...
                            I would be grateful to you if you consider my reuest..

                            Comment

                            • avinash jain
                              New Member
                              • Aug 2007
                              • 12

                              #15
                              avoid If/Else statements using inheritance

                              Hi to all
                              Could any one tell me how to avoid if/else statements uisng inheritance..

                              Comment

                              Working...