Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. The Lounge
  3. Code style question - disparate then/else sizes

Code style question - disparate then/else sizes

Scheduled Pinned Locked Moved The Lounge
questionlinux
39 Posts 24 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D Dan Neely

    If you have an if/else with one branch significantly larger than the other, how do you normally order them when keeping the conditional understandable doesn't drive the decision?

    if (x < 10)
    {
    //short code block
    }
    else
    {
    //long code block
    }

    of like this:

    if (10 <= x)
    {
    //long code block
    }
    else
    {
    //short code block
    }

    Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

    M Offline
    M Offline
    Maximilien
    wrote on last edited by
    #5

    don't know it this will help but I always try to keep the "normal" conditional path in the "if" part instead of the "else" part of the condition, so if it means testing on "!=" instead of "==" I will do it.


    Maximilien Lincourt Your Head A Splode - Strong Bad

    D 1 Reply Last reply
    0
    • R Robert Royall

      Generally it's always a bad idea to compare a literal to a variable ("10<=X") because it tends to throw people who look at it too fast. That being said, most people tend to believe that you should set the conditional to be the most likely case to run - in your example case, if you think that x will be a value less than 10 more often than it will be 10 or more.

      Please don't bother me... I'm hacking right now. Don't look at me like that - doesn't anybody remember what "hacking" really means? :sigh:

      J Offline
      J Offline
      Jorgen Sigvardsson
      wrote on last edited by
      #6

      Robert Royall wrote:

      Generally it's always a bad idea to compare a literal to a variable ("10<=X") because it tends to throw people who look at it too fast.

      On the other hand, it doesn't invite problems like these:

      if(x = 0) { ... }

      -- Kein Mitleid Für Die Mehrheit

      G 1 Reply Last reply
      0
      • D Dan Neely

        If you have an if/else with one branch significantly larger than the other, how do you normally order them when keeping the conditional understandable doesn't drive the decision?

        if (x < 10)
        {
        //short code block
        }
        else
        {
        //long code block
        }

        of like this:

        if (10 <= x)
        {
        //long code block
        }
        else
        {
        //short code block
        }

        Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

        P Offline
        P Offline
        Pawel Krakowiak
        wrote on last edited by
        #7

        Don't care, although if I had to choose I'd put the short one first.

        Kind regards, Pawel Krakowiak Miraculum Software[^]

        1 Reply Last reply
        0
        • D Dan Neely

          If you have an if/else with one branch significantly larger than the other, how do you normally order them when keeping the conditional understandable doesn't drive the decision?

          if (x < 10)
          {
          //short code block
          }
          else
          {
          //long code block
          }

          of like this:

          if (10 <= x)
          {
          //long code block
          }
          else
          {
          //short code block
          }

          Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

          E Offline
          E Offline
          El Corazon
          wrote on last edited by
          #8

          I agree with the others saying make the first part the primary. I treat if/elses as primary and exception regardless of size. There are times when handling the exceptional case requires more work and is sometimes longer and other times where it is not, but in general the majority of your cases should go through the if, not the else. If the latter is true, you may have a design issue you were not aware of, in which case it is good to know through optimization steps that your assumptions were wrong and decide how to correct them. Knowing that the primary path is in the first block means you can easily find when you made an improper assumption, if code directs more often to the else, it is time to find out why, not just flip the if around. When you understand why, and the fix is flip the code around, that is fine, but it could be that there is an issue in the input of x that you didn't know about, and fixing it causes the code to direct through the proper section more often. Keeping the code this uniform as primary and exception leads to easier times optimizing if you keep up with it, that is.

          _________________________ Asu no koto o ieba, tenjo de nezumi ga warau. Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)

          1 Reply Last reply
          0
          • D Dan Neely

            If you have an if/else with one branch significantly larger than the other, how do you normally order them when keeping the conditional understandable doesn't drive the decision?

            if (x < 10)
            {
            //short code block
            }
            else
            {
            //long code block
            }

            of like this:

            if (10 <= x)
            {
            //long code block
            }
            else
            {
            //short code block
            }

            Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

            M Offline
            M Offline
            Mike Dimmick
            wrote on last edited by
            #9

            As others have said, I would tend to put the positive, normal case in the 'if' arm and the exception case in the 'else' part. If that means that the 'else' part confuses the flow of the normal logic, pull out the 'else' part into a separate function. This can have the effect of speeding up the normal flow because more of the normal flow fits into the processor's cache! Microsoft actually use this approach in Windows - they seem to have a tool which will pull out error-handling code onto a different page from the regular code path, so that the error path isn't even paged in until needed.

            DoEvents: Generating unexpected recursion since 1991

            1 Reply Last reply
            0
            • D Dan Neely

              If you have an if/else with one branch significantly larger than the other, how do you normally order them when keeping the conditional understandable doesn't drive the decision?

              if (x < 10)
              {
              //short code block
              }
              else
              {
              //long code block
              }

              of like this:

              if (10 <= x)
              {
              //long code block
              }
              else
              {
              //short code block
              }

              Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

              T Offline
              T Offline
              Tim Carmichael
              wrote on last edited by
              #10

              As others have said, I would prefer to use the primary result with the 'if', and then other conditions in reducing order of appearance (assuming there may be an 'elseif' or two...) On a similar note, if using a 'case' statement, I prefer my conditions in alphabetical/numerical order. Tim

              1 Reply Last reply
              0
              • D Dan Neely

                If you have an if/else with one branch significantly larger than the other, how do you normally order them when keeping the conditional understandable doesn't drive the decision?

                if (x < 10)
                {
                //short code block
                }
                else
                {
                //long code block
                }

                of like this:

                if (10 <= x)
                {
                //long code block
                }
                else
                {
                //short code block
                }

                Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

                R Offline
                R Offline
                Ray Cassick
                wrote on last edited by
                #11

                I have always arranged my code to have the most used path first. Not sure if it makes a difference at compile time with regards to efficiency or anything, I just got used to doing it that way.


                My Blog[^]
                FFRF[^]


                1 Reply Last reply
                0
                • R Robert Royall

                  Generally it's always a bad idea to compare a literal to a variable ("10<=X") because it tends to throw people who look at it too fast. That being said, most people tend to believe that you should set the conditional to be the most likely case to run - in your example case, if you think that x will be a value less than 10 more often than it will be 10 or more.

                  Please don't bother me... I'm hacking right now. Don't look at me like that - doesn't anybody remember what "hacking" really means? :sigh:

                  D Offline
                  D Offline
                  Dan Neely
                  wrote on last edited by
                  #12

                  I always write my inequalities with the low on the left. After a decade and a half of being programmed that way by math classes in school any other ordering of an interval throws me.

                  Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

                  1 Reply Last reply
                  0
                  • M Maximilien

                    don't know it this will help but I always try to keep the "normal" conditional path in the "if" part instead of the "else" part of the condition, so if it means testing on "!=" instead of "==" I will do it.


                    Maximilien Lincourt Your Head A Splode - Strong Bad

                    D Offline
                    D Offline
                    Dan Neely
                    wrote on last edited by
                    #13

                    That's not an unreasonable standard if you know which branch is preferred. In this case I'm reverse engineering requirements out of existing code. I don't know which case is preferential, and am 95% sure based on history that when the first version was written there wasn't an else clause at all, so I can't get any insight that way. At present I'm not looking to actually refactor it. Even if I was redoing the VBA instead of converting similar C# code into managed COM objects to use only a single codebase I've got much higher priorities to cleanup than reordering if/else pairs.

                    Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

                    1 Reply Last reply
                    0
                    • M Member 96

                      Never thought about it to be honest and don't try to do it any particular way. I guess if I had to choose it would make far more sense to put the short code block first for readability so it doesn't get lost in the long code block. I always slap a #region directive around a long code block though so maybe that's why I never noticed before.


                      When everyone is a hero no one is a hero.

                      D Offline
                      D Offline
                      David Stone
                      wrote on last edited by
                      #14

                      John C wrote:

                      I always slap a #region directive around a long code block though so maybe that's why I never noticed before.

                      Not a big fan of refactoring, eh John? ;)

                      M 1 Reply Last reply
                      0
                      • D Dan Neely

                        If you have an if/else with one branch significantly larger than the other, how do you normally order them when keeping the conditional understandable doesn't drive the decision?

                        if (x < 10)
                        {
                        //short code block
                        }
                        else
                        {
                        //long code block
                        }

                        of like this:

                        if (10 <= x)
                        {
                        //long code block
                        }
                        else
                        {
                        //short code block
                        }

                        Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

                        S Offline
                        S Offline
                        Sebastien Lachance
                        wrote on last edited by
                        #15

                        I would myself put the short code block before, but it depend on the condition. I try to avoid negative (if (!true))condition in the if clause. :doh:

                        My Blog

                        1 Reply Last reply
                        0
                        • J Jorgen Sigvardsson

                          Robert Royall wrote:

                          Generally it's always a bad idea to compare a literal to a variable ("10<=X") because it tends to throw people who look at it too fast.

                          On the other hand, it doesn't invite problems like these:

                          if(x = 0) { ... }

                          -- Kein Mitleid Für Die Mehrheit

                          G Offline
                          G Offline
                          Gary Wheeler
                          wrote on last edited by
                          #16

                          Compilers have been capable of issuing diagnostic messages for that sort of thing for over ten years now. I think the loss of readability of

                          if (0 == x) { /* ... */ }

                          far outweighs any benefit in detecting the incorrect operator.


                          Software Zen: delete this;

                          1 Reply Last reply
                          0
                          • D David Stone

                            John C wrote:

                            I always slap a #region directive around a long code block though so maybe that's why I never noticed before.

                            Not a big fan of refactoring, eh John? ;)

                            M Offline
                            M Offline
                            Member 96
                            wrote on last edited by
                            #17

                            I saw your wink, but I'm not sure what refactoring has to do with putting regions around code blocks for readability. I'm not a big fan of writing sloppy code in the first place and poor designs that will clearly need refactoring later but that being said I've been spending nearly the entire last week refactoring my setup and deployment system for a very large app.


                            When everyone is a hero no one is a hero.

                            1 Reply Last reply
                            0
                            • D Dan Neely

                              If you have an if/else with one branch significantly larger than the other, how do you normally order them when keeping the conditional understandable doesn't drive the decision?

                              if (x < 10)
                              {
                              //short code block
                              }
                              else
                              {
                              //long code block
                              }

                              of like this:

                              if (10 <= x)
                              {
                              //long code block
                              }
                              else
                              {
                              //short code block
                              }

                              Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

                              A Offline
                              A Offline
                              Andy Brummer
                              wrote on last edited by
                              #18

                              As much as possible I try to write each function as a linear segment of code. About 75% or higher of my if statements are checking for conditions that result in exiting the method early rather then requiring an else. I find this much easier to follow as most of the code that actually causes side effects is close to the end of the method, and the rest is filters that lets execution down to the code that "does stuff". When I do write else blocks I usually put the shorter block first.


                              This blanket smells like ham

                              M T 2 Replies Last reply
                              0
                              • R Robert Royall

                                Generally it's always a bad idea to compare a literal to a variable ("10<=X") because it tends to throw people who look at it too fast. That being said, most people tend to believe that you should set the conditional to be the most likely case to run - in your example case, if you think that x will be a value less than 10 more often than it will be 10 or more.

                                Please don't bother me... I'm hacking right now. Don't look at me like that - doesn't anybody remember what "hacking" really means? :sigh:

                                M Offline
                                M Offline
                                Member 96
                                wrote on last edited by
                                #19

                                Robert Royall wrote:

                                Generally it's always a bad idea to compare a literal to a variable

                                Really? I've found it to be a good practice for decades now. I usually only use it in straight equality comparisons though as other types are a bit harder to read.


                                When everyone is a hero no one is a hero.

                                R 1 Reply Last reply
                                0
                                • A Andy Brummer

                                  As much as possible I try to write each function as a linear segment of code. About 75% or higher of my if statements are checking for conditions that result in exiting the method early rather then requiring an else. I find this much easier to follow as most of the code that actually causes side effects is close to the end of the method, and the rest is filters that lets execution down to the code that "does stuff". When I do write else blocks I usually put the shorter block first.


                                  This blanket smells like ham

                                  M Offline
                                  M Offline
                                  Member 96
                                  wrote on last edited by
                                  #20

                                  Andy Brummer wrote:

                                  About 75% or higher of my if statements are checking for conditions that result in exiting the method early rather then requiring an else

                                  Yes! That's actually what I do in practice more often than not. I call it "short circuiting" and at every opportunity I look for a short circuit that can go early in the method. All those years of coding on slow hardware I guess just make it a habit.


                                  When everyone is a hero no one is a hero.

                                  E 1 Reply Last reply
                                  0
                                  • M Member 96

                                    Andy Brummer wrote:

                                    About 75% or higher of my if statements are checking for conditions that result in exiting the method early rather then requiring an else

                                    Yes! That's actually what I do in practice more often than not. I call it "short circuiting" and at every opportunity I look for a short circuit that can go early in the method. All those years of coding on slow hardware I guess just make it a habit.


                                    When everyone is a hero no one is a hero.

                                    E Offline
                                    E Offline
                                    El Corazon
                                    wrote on last edited by
                                    #21

                                    John C wrote:

                                    Yes! That's actually what I do in practice more often than not. I call it "short circuiting" and at every opportunity I look for a short circuit that can go early in the method. All those years of coding on slow hardware I guess just make it a habit.

                                    It is still a matter of putting most execution up front. The knowledge that you have to weed out a majority to find a solution is common. For instance simulating a sensor, Range cuts out the largest land area, if your sensor's range is 2km then you just cut out 99.999% of of the earth or something like that in one conditional. Now you can narrow it down based on other parameters, each step bringing you close to the desired item and action. Even those with big hardware should pay attention to such things. If you have 1000 items to find one of interest, and you have a zillion other actions to accomplish as well, the faster you weed out the failures the better so that you can do other things. There is always more computation you can add on a fast machine, better to use that in the fancy additions than the humdrum activities, so the faster your code the better. :-D

                                    _________________________ Asu no koto o ieba, tenjo de nezumi ga warau. Talk about things of tomorrow and the mice in the ceiling laugh. (Japanese Proverb)

                                    1 Reply Last reply
                                    0
                                    • D Dan Neely

                                      If you have an if/else with one branch significantly larger than the other, how do you normally order them when keeping the conditional understandable doesn't drive the decision?

                                      if (x < 10)
                                      {
                                      //short code block
                                      }
                                      else
                                      {
                                      //long code block
                                      }

                                      of like this:

                                      if (10 <= x)
                                      {
                                      //long code block
                                      }
                                      else
                                      {
                                      //short code block
                                      }

                                      Otherwise [Microsoft is] toast in the long term no matter how much money they've got. They would be already if the Linux community didn't have it's head so firmly up it's own command line buffer that it looks like taking 15 years to find the desktop. -- Matthew Faithfull

                                      C Offline
                                      C Offline
                                      Christian Graus
                                      wrote on last edited by
                                      #22

                                      There's an error in your code :-) I'd probably refactor the long block to a method, if it was really long ( and then make it first as it would be the shortest ), or if it wasn't *that* long, I'd put the short block first.

                                      Christian Graus - Microsoft MVP - C++ "also I don't think "TranslateOneToTwoBillion OneHundredAndFortySevenMillion FourHundredAndEightyThreeThousand SixHundredAndFortySeven()" is a very good choice for a function name" - SpacixOne ( offering help to someone who really needed it ) ( spaces added for the benefit of people running at < 1280x1024 )

                                      1 Reply Last reply
                                      0
                                      • V Vasudevan Deepak Kumar

                                        If the language in C#, then wouldn't #region CodeSnippet #endregion also lend some helping hands?

                                        Vasudevan Deepak Kumar Personal Homepage
                                        Tech Gossips
                                        A pessimist sees only the dark side of the clouds, and mopes; a philosopher sees both sides, and shrugs; an optimist doesn't see the clouds at all - he's walking on them. --Leonard Louis Levinson

                                        J Offline
                                        J Offline
                                        JoeSox
                                        wrote on last edited by
                                        #23

                                        I :love: #region !!

                                        Later, JoeSox CPMCv1.0 ? humanaiproject.org ? Last.fm ? pswrdgen

                                        B 1 Reply Last reply
                                        0
                                        • M Member 96

                                          Robert Royall wrote:

                                          Generally it's always a bad idea to compare a literal to a variable

                                          Really? I've found it to be a good practice for decades now. I usually only use it in straight equality comparisons though as other types are a bit harder to read.


                                          When everyone is a hero no one is a hero.

                                          R Offline
                                          R Offline
                                          Robert Royall
                                          wrote on last edited by
                                          #24

                                          Thanks for taking my quote out of context. ;P

                                          Robert Royall wrote:

                                          Generally it's always a bad idea to compare a literal to a variable because it tends to throw people who look at it too fast.

                                          How many maintenance programmers scanning through an assignment like (10 <= x) are going to see (x <= 10) instead? Granted, if you only use it for equality it's obviously not a problem no matter how you read it.

                                          Please don't bother me... I'm hacking right now. Don't look at me like that - doesn't anybody remember what "hacking" really means? :sigh:

                                          1 Reply Last reply
                                          0
                                          Reply
                                          • Reply as topic
                                          Log in to reply
                                          • Oldest to Newest
                                          • Newest to Oldest
                                          • Most Votes


                                          • Login

                                          • Don't have an account? Register

                                          • Login or register to search.
                                          • First post
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • World
                                          • Users
                                          • Groups