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

    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
        • 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.

          T Offline
          T Offline
          Tom Delany
          wrote on last edited by
          #25

          I like #region as well, but it drives my co-worker batty. *sigh* :sigh:

          WE ARE DYSLEXIC OF BORG. Refutance is systile. Your a$$ will be laminated.

          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
            Marc Clifton
            wrote on last edited by
            #26

            if statements are evil. If they can't be handled by inheritence, or it doesn't make sense to express the logic in a state or decision graph, then (no pun intended on this sentence):

            if ([some expression]
            {
            DoThis();
            }
            else
            {
            DoThat();
            }

            rather than embedding a bunch of probably re-usable code in the statement itself. Besides, it makes it a lot more readable as to what you're doing. Of course, yes, there are exceptions. Marc

            Thyme In The Country Interacx My Blog

            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

              T Offline
              T Offline
              Tom Delany
              wrote on last edited by
              #27

              Andy Brummer wrote:

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

              A little off topic: When you do that, do you just exit the method at that point? It was always drilled into my head that all methods (in the old days we called them "functions") should only have one exit point, but if I try to follow that mandate in situations like you described above, I end up jumping through hoops to make that happen, so I often tend to be "guilty" of simply putting a "return" inside my if at the point I want it to exit. Hopefully that does not brand me as a horrible coder. I had one coworker who thought it was neat to get around that (in C/C++) by coding something like:      do      {          if (somecondition)              break;          if (someothercondition)              break;          //etc.      } while (false) (It will execute the above loop only one time as coded.) I always thought that was simply horrible!

              WE ARE DYSLEXIC OF BORG. Refutance is systile. Your a$$ will be laminated.

              D A M E 4 Replies Last reply
              0
              • T Tom Delany

                Andy Brummer wrote:

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

                A little off topic: When you do that, do you just exit the method at that point? It was always drilled into my head that all methods (in the old days we called them "functions") should only have one exit point, but if I try to follow that mandate in situations like you described above, I end up jumping through hoops to make that happen, so I often tend to be "guilty" of simply putting a "return" inside my if at the point I want it to exit. Hopefully that does not brand me as a horrible coder. I had one coworker who thought it was neat to get around that (in C/C++) by coding something like:      do      {          if (somecondition)              break;          if (someothercondition)              break;          //etc.      } while (false) (It will execute the above loop only one time as coded.) I always thought that was simply horrible!

                WE ARE DYSLEXIC OF BORG. Refutance is systile. Your a$$ will be laminated.

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

                Tom Delany wrote:

                A little off topic: When you do that, do you just exit the method at that point? It was always drilled into my head that all methods (in the old days we called them "functions") should only have one exit point, but if I try to follow that mandate in situations like you described above, I end up jumping through hoops to make that happen, so I often tend to be "guilty" of simply putting a "return" inside my if at the point I want it to exit. Hopefully that does not brand me as a horrible coder.

                I do the same with a caveat, if I have more than 2 or 3 conditions (or the single condition is really complex), I move all the validation into a seperate bool function, splatter a mess of return false's thoughout, and then only have 1 validation exit at the very beginning of the function.

                Tom Delany wrote:

                (It will execute the above loop only one time as coded.) I always thought that was simply horrible!

                :confused: X| :omg: :wtf:

                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 Marc Clifton

                  if statements are evil. If they can't be handled by inheritence, or it doesn't make sense to express the logic in a state or decision graph, then (no pun intended on this sentence):

                  if ([some expression]
                  {
                  DoThis();
                  }
                  else
                  {
                  DoThat();
                  }

                  rather than embedding a bunch of probably re-usable code in the statement itself. Besides, it makes it a lot more readable as to what you're doing. Of course, yes, there are exceptions. Marc

                  Thyme In The Country Interacx My Blog

                  R Offline
                  R Offline
                  Robert Surtees
                  wrote on last edited by
                  #29

                  Marc Clifton wrote:

                  if statements are evil.

                  First they make goto's evil, and now if's? I think it's time for me to retire. :sigh:

                  M 1 Reply Last reply
                  0
                  • R Robert Surtees

                    Marc Clifton wrote:

                    if statements are evil.

                    First they make goto's evil, and now if's? I think it's time for me to retire. :sigh:

                    M Offline
                    M Offline
                    Marc Clifton
                    wrote on last edited by
                    #30

                    Robert Surtees wrote:

                    First they make goto's evil, and now if's? I think it's time for me to retire.

                    I'm actually of the mind that gotos are less evil than if's. An if statement results in one or more conditional code branches, which is harder to test than an unconditional goto. When I write an if nowadays, I consciously think "what is the else" and "ok, now I have to test BOTH conditions." I end up often looking at a better way to code the routine that doesn't require an if, and surprisingly, a lot of times I find a way. Marc

                    Thyme In The Country Interacx My Blog

                    R 1 Reply Last reply
                    0
                    • T Tom Delany

                      Andy Brummer wrote:

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

                      A little off topic: When you do that, do you just exit the method at that point? It was always drilled into my head that all methods (in the old days we called them "functions") should only have one exit point, but if I try to follow that mandate in situations like you described above, I end up jumping through hoops to make that happen, so I often tend to be "guilty" of simply putting a "return" inside my if at the point I want it to exit. Hopefully that does not brand me as a horrible coder. I had one coworker who thought it was neat to get around that (in C/C++) by coding something like:      do      {          if (somecondition)              break;          if (someothercondition)              break;          //etc.      } while (false) (It will execute the above loop only one time as coded.) I always thought that was simply horrible!

                      WE ARE DYSLEXIC OF BORG. Refutance is systile. Your a$$ will be laminated.

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

                      I always thought that came from long overly complicated methods that had a lot of state to "unroll" when you exited from the method. Also, if you are using raw new/delete calls, then this is almost impossible to do. In C++ it really requires using some kind of smart pointer to support. If I'm not able to cleanly throw an exception or exit with a simple return then I simplify the method until I can. If there is too much going on, I'll even create a transactional object that I can just throw away. I agree with you about that do while crap. Ugh.


                      This blanket smells like ham

                      T 1 Reply Last reply
                      0
                      • T Tom Delany

                        Andy Brummer wrote:

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

                        A little off topic: When you do that, do you just exit the method at that point? It was always drilled into my head that all methods (in the old days we called them "functions") should only have one exit point, but if I try to follow that mandate in situations like you described above, I end up jumping through hoops to make that happen, so I often tend to be "guilty" of simply putting a "return" inside my if at the point I want it to exit. Hopefully that does not brand me as a horrible coder. I had one coworker who thought it was neat to get around that (in C/C++) by coding something like:      do      {          if (somecondition)              break;          if (someothercondition)              break;          //etc.      } while (false) (It will execute the above loop only one time as coded.) I always thought that was simply horrible!

                        WE ARE DYSLEXIC OF BORG. Refutance is systile. Your a$$ will be laminated.

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

                        Yes, always an early return. Don't futz around with loops: the programmer's expectation is that there are at least some circumstances where the loop will be executed at least once. It's basically trying to avoid two programming taboos, drummed into us by the idiots we call professors: single entry, single exit; and that goto is evil. Neither are correct.

                        DoEvents: Generating unexpected recursion since 1991

                        1 Reply Last reply
                        0
                        • M Marc Clifton

                          Robert Surtees wrote:

                          First they make goto's evil, and now if's? I think it's time for me to retire.

                          I'm actually of the mind that gotos are less evil than if's. An if statement results in one or more conditional code branches, which is harder to test than an unconditional goto. When I write an if nowadays, I consciously think "what is the else" and "ok, now I have to test BOTH conditions." I end up often looking at a better way to code the routine that doesn't require an if, and surprisingly, a lot of times I find a way. Marc

                          Thyme In The Country Interacx My Blog

                          R Offline
                          R Offline
                          Robert Surtees
                          wrote on last edited by
                          #33

                          lol -- probably should have used a smiley instead of a sigh. Reducing complexity is always a Good Thing.

                          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
                            Ravi Bhavnani
                            wrote on last edited by
                            #34

                            I'd place the shorter block first so that you don't have to scroll down to check for the existence of an else clause. Of course, this assumes (as you mentioned) that your decision is isn't driven by the need to have positive logic in the if test. /ravi

                            This is your brain on Celcius Home | Music | Articles | Freeware ravib(at)ravib(dot)com

                            1 Reply Last reply
                            0
                            • A Andy Brummer

                              I always thought that came from long overly complicated methods that had a lot of state to "unroll" when you exited from the method. Also, if you are using raw new/delete calls, then this is almost impossible to do. In C++ it really requires using some kind of smart pointer to support. If I'm not able to cleanly throw an exception or exit with a simple return then I simplify the method until I can. If there is too much going on, I'll even create a transactional object that I can just throw away. I agree with you about that do while crap. Ugh.


                              This blanket smells like ham

                              T Offline
                              T Offline
                              Tom Delany
                              wrote on last edited by
                              #35

                              Andy Brummer wrote:

                              I agree with you about that do while crap. Ugh.

                              Aaarghhh!!! :omg: :wtf: I found it in "Coding Horrors", and it was not supposed to be the "horror": http://www.codeproject.com/Feature/CodingHorrors.aspx?msg=2323029#xx2323029xx[^]

                              WE ARE DYSLEXIC OF BORG. Refutance is systile. Your a$$ will be laminated.

                              1 Reply Last reply
                              0
                              • T Tom Delany

                                Andy Brummer wrote:

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

                                A little off topic: When you do that, do you just exit the method at that point? It was always drilled into my head that all methods (in the old days we called them "functions") should only have one exit point, but if I try to follow that mandate in situations like you described above, I end up jumping through hoops to make that happen, so I often tend to be "guilty" of simply putting a "return" inside my if at the point I want it to exit. Hopefully that does not brand me as a horrible coder. I had one coworker who thought it was neat to get around that (in C/C++) by coding something like:      do      {          if (somecondition)              break;          if (someothercondition)              break;          //etc.      } while (false) (It will execute the above loop only one time as coded.) I always thought that was simply horrible!

                                WE ARE DYSLEXIC OF BORG. Refutance is systile. Your a$$ will be laminated.

                                E Offline
                                E Offline
                                Erik Funkenbusch
                                wrote on last edited by
                                #36

                                Actually, that's not horrible at all. It's a very slick and elegant way to handle the problem. I used to use this form: #define EVER ;; for(EVER) { if (blah) break; ... break; } Your co-workers solution solves the problem of accidentally forgetting the final break (which i've been bit by a few times). I don't really call that "jumping through hoops" though, It's a pretty common pattern, therefore programmers will expect it. The "one entrance, one exit" rule was put in place because it encourages simplification of the code. Lots of returns within code is often a symptom of overly complex code. It's easier to just return than to clean up after yourself.

                                -- Where are we going? And why am I in this handbasket?

                                T 1 Reply Last reply
                                0
                                • J JoeSox

                                  I :love: #region !!

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

                                  B Offline
                                  B Offline
                                  Brady Kelly
                                  wrote on last edited by
                                  #37

                                  So do I, but definitely not in code blocs.

                                  My head asplode!

                                  Calling all South African developers! Your participation in this local dev community will be mutually beneficial, to you and us.

                                  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

                                    realJSOPR Offline
                                    realJSOPR Offline
                                    realJSOP
                                    wrote on last edited by
                                    #38

                                    I don't do it by size of the code block. I do it according to the result of the if statement. I do the "true" result first, and the "false" result second.

                                    "Why don't you tie a kerosene-soaked rag around your ankles so the ants won't climb up and eat your candy ass..." - Dale Earnhardt, 1997
                                    -----
                                    "...the staggering layers of obscenity in your statement make it a work of art on so many levels." - Jason Jystad, 10/26/2001

                                    1 Reply Last reply
                                    0
                                    • E Erik Funkenbusch

                                      Actually, that's not horrible at all. It's a very slick and elegant way to handle the problem. I used to use this form: #define EVER ;; for(EVER) { if (blah) break; ... break; } Your co-workers solution solves the problem of accidentally forgetting the final break (which i've been bit by a few times). I don't really call that "jumping through hoops" though, It's a pretty common pattern, therefore programmers will expect it. The "one entrance, one exit" rule was put in place because it encourages simplification of the code. Lots of returns within code is often a symptom of overly complex code. It's easier to just return than to clean up after yourself.

                                      -- Where are we going? And why am I in this handbasket?

                                      T Offline
                                      T Offline
                                      Tom Delany
                                      wrote on last edited by
                                      #39

                                      Fair enough. Cheers,

                                      WE ARE DYSLEXIC OF BORG. Refutance is systile. Your a$$ will be laminated.

                                      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