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. Programming style

Programming style

Scheduled Pinned Locked Moved The Lounge
c++architecture
46 Posts 27 Posters 4 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.
  • C Christian Graus

    I tend to the second also, if it's a case of 'if this isn't true, I can't do anything here', especially when I presume that it will always be true, I just want to make sure I add checks for my assumptions. Especially in event code, which the framework may call before I want it called ( as in, during initialisation ), and my code will stop an intermittent crash, or make the designer work, but once the program is up and running, I can be sure the check is never going to fail.

    Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

    P Offline
    P Offline
    Paul Conrad
    wrote on last edited by
    #18

    I would actually give it some kind of return value. In this case, return a false if nothing can be done, or something like that.

    "The clue train passed his station without stopping." - John Simmons / outlaw programmer

    1 Reply Last reply
    0
    • C Christian Graus

      As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

      Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

      R Offline
      R Offline
      Rama Krishna Vavilala
      wrote on last edited by
      #19

      For C++ the first one. I think it was something to do with the compiler code generation and stack winding. The C++ compiler generated lot more code in machine language when a function had multiple return points. For C#, Java, VB.NET etc, the second one: Since the code gets compiled to IL first and then into Machine language. My experiments revealed that there was not much difference in code generation.

      1 Reply Last reply
      0
      • C Christian Graus

        As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

        Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

        Richard Andrew x64R Offline
        Richard Andrew x64R Offline
        Richard Andrew x64
        wrote on last edited by
        #20

        I like the one-entrance-one-exit style because I think it is technically beautiful. And I like the other style because it is easier conceptualize the logic. I would prefer to use the first way as long as the decisions don't become too numerous and indented, and I would switch to the second way as soon as the first way became unwieldy. That's actually one of the ways we technical nerds gain an opportunity for artistic expression. Don't tell yourself that you must choose one or the other. Tell yourself that you will know when to use either one!

        -------------------------------- "All that is necessary for the forces of evil to win in the world is for enough good men to do nothing" -- Edmund Burke

        1 Reply Last reply
        0
        • C Christian Graus

          As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

          Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

          L Offline
          L Offline
          Luis Alonso Ramos
          wrote on last edited by
          #21

          I use the second style. Although multiple exit points, it is still top-down, so debugging or tracing how things happen is not so bad. With the first case if you have multiple conditions to test, you end up with code staring on the 40th column and a lot of braces. I guess that is more confusing than keeping the main code at the first ident label. Also, the multiple-exit points for debugging argument is slashed by saying that if the funcion returns null at the very end, you still have to find which of the 8 ifs failed.

          Luis Alonso Ramos Intelectix Chihuahua, Mexico

          My Blog!

          1 Reply Last reply
          0
          • S Shog9 0

            The last one. I hate tracing all the way through a method - whether reading it or actually stepping in the debugger - only to find that there is no alternate code path. If it's a sanity check, if the method does nothing when the condition fails, then i want to know that from the start. I mean, just think about it - if you were asking me the question aloud, "Shog, what happens if btn is null?" - and i replied, "well, CG, if it isn't null, then we change the text and the color and attach a little icon which we load from resources, and if the user is logged in then we enable it but otherwise we disable it and set up a tool tip with a little message explaining that they have to log in, and"... at this point, you should have already hit me upside the head with a 2x4, having had plenty of time to go out and buy a 2x4 while i was busy reading off the novella that was the tooltip text... My point here is that you wouldn't put up with that sort of madness in any other medium, so why allow it in code? Also, i hate excessive indentation.

            every night, i kneel at the foot of my bed and thank the Great Overseeing Politicians for protecting my freedoms by reducing their number, as if they were deer in a state park. -- Chris Losinger, Online Poker Players?

            A Offline
            A Offline
            achimera
            wrote on last edited by
            #22

            > Also, i hate excessive indentation. One day when reviewing resumes, a coworker told me -- never read each from top to bottom -- read backwards -- from the bottom up -- because the most important information is at the bottom, not the top. I think that applies to your reply as well. Obviously, your ultimate point was that you hate excessive indentation. Excessive indentation, however (as per best programming practices), is not solved by multiple returns -- but instead through other means.

            S 1 Reply Last reply
            0
            • A achimera

              > Also, i hate excessive indentation. One day when reviewing resumes, a coworker told me -- never read each from top to bottom -- read backwards -- from the bottom up -- because the most important information is at the bottom, not the top. I think that applies to your reply as well. Obviously, your ultimate point was that you hate excessive indentation. Excessive indentation, however (as per best programming practices), is not solved by multiple returns -- but instead through other means.

              S Offline
              S Offline
              Shog9 0
              wrote on last edited by
              #23

              achimera wrote:

              Excessive indentation, however (as per best programming practices), is not solved by multiple returns -- but instead through other means.

              Wait, are you implying i need to reduce my tab size... :suss: ;)

              every night, i kneel at the foot of my bed and thank the Great Overseeing Politicians for protecting my freedoms by reducing their number, as if they were deer in a state park. -- Chris Losinger, Online Poker Players?

              R 1 Reply Last reply
              0
              • C Christian Graus

                As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

                Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

                L Offline
                L Offline
                Leslie Sanford
                wrote on last edited by
                #24

                Christian Graus wrote:

                As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks.

                I call these "guards." Typically, I set them off from the rest of the method:

                public void SetSomeValue(int value)
                {
                #region Guard

                if(value == someValue)
                {
                    return;
                }
                
                #endregion
                
                // Expensive operation here.
                

                }

                The guard prevents the method from running if doing so would be redundant and more importantly expensive. I look at guards as being different from preconditions. It's possible for the preconditions of a method to have been met but to have triggered the guard nontheless. As long as the postconditions of the method are still met, then everything's cool. After the guard, I generally avoid early returns, but bend this rule from time to time.

                1 Reply Last reply
                0
                • S Shog9 0

                  The last one. I hate tracing all the way through a method - whether reading it or actually stepping in the debugger - only to find that there is no alternate code path. If it's a sanity check, if the method does nothing when the condition fails, then i want to know that from the start. I mean, just think about it - if you were asking me the question aloud, "Shog, what happens if btn is null?" - and i replied, "well, CG, if it isn't null, then we change the text and the color and attach a little icon which we load from resources, and if the user is logged in then we enable it but otherwise we disable it and set up a tool tip with a little message explaining that they have to log in, and"... at this point, you should have already hit me upside the head with a 2x4, having had plenty of time to go out and buy a 2x4 while i was busy reading off the novella that was the tooltip text... My point here is that you wouldn't put up with that sort of madness in any other medium, so why allow it in code? Also, i hate excessive indentation.

                  every night, i kneel at the foot of my bed and thank the Great Overseeing Politicians for protecting my freedoms by reducing their number, as if they were deer in a state park. -- Chris Losinger, Online Poker Players?

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

                  Well said.


                  This blanket smells like ham

                  1 Reply Last reply
                  0
                  • C Christian Graus

                    As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

                    Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

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

                    It depends how much state the method is carrying along with it when you exit. As long as you don't have to delete objects or readjust state of shared objects in order to return from the method I say go for it. The reason multiple exit points are considered bad is that if you have to clean up your state before you return, you end up duplicating that cleanup with every exit point, which leads to duplicate code which is hard to maintain. In procedural code, there isn't any way to get around that other then writing cleanup methods, which is ugly since you are writing an extra function just so you can exit cleanly from another method. In object oriented code you can have a number of classes that perform generic operations and reset state on destruction/disposal so you can manage state cleanly, and still focus on writing the code that is easiest to maintain. Also, I never write an if statement in under 2 lines.

                    if (btn == null)
                    return;

                    or

                    if (btn == null)
                    {
                    //do something
                    //do something else
                    }


                    This blanket smells like ham

                    1 Reply Last reply
                    0
                    • A achimera

                      IMO -- multiple exit points for a function, is akin to the dreaded "goto" -- in that it is a poor programming practice. Personally, I prefer nested code, where you wind in, and then back out -- there is a certain degree of balance and beauty to it when done correct -- however I know I am probably in the minority. The authoritive solution to excessive nesting is supposed to be the creation of more modular functions and/or the introduction of the entire concept of exception handling -- not more returns.

                      A Offline
                      A Offline
                      Andrew Drummond
                      wrote on last edited by
                      #27

                      the second style is the better in this case. in order to not feel so 'dirty' think of it as a form of pre-condition check - if the language supported pre and post conditions you would do the check there. multiple exit points from within the method are not such a great idea, as Jackson said. The key thing is to keep the complexity of the code down. The early exits for parameter checks accomplish this - exit points in the middle of the method are unlikly to and it might be better to restructure the code and/or create more functionaly cohesive methods. In reply to another email you don't really need to put comments in here as it is pretty obvious what is going on as the checks are so early.

                      1 Reply Last reply
                      0
                      • C Christian Graus

                        As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

                        Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #28

                        The first, it is clear why you are returning.

                        Visit http://www.readytogiveup.com/[^] and do something special today.

                        1 Reply Last reply
                        0
                        • C Christian Graus

                          As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

                          Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

                          W Offline
                          W Offline
                          WillemM
                          wrote on last edited by
                          #29

                          I like the second one, since that one supports the "happy flow" principle I use at work. This principle states that the code should have a main flow that runs all the way to the end and not have too much if() { } else { if() { } else { } } statements.

                          WM. What about weapons of mass-construction? "What? Its an Apple MacBook Pro. They are sexy!" - Paul Watson My blog

                          1 Reply Last reply
                          0
                          • C Christian Graus

                            As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

                            Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

                            K Offline
                            K Offline
                            Kevin McFarlane
                            wrote on last edited by
                            #30

                            I'm similar to you. I generally go for one exit point but occasionally it's simpler to return after an initial check fails.

                            Kevin

                            1 Reply Last reply
                            0
                            • S Shog9 0

                              The last one. I hate tracing all the way through a method - whether reading it or actually stepping in the debugger - only to find that there is no alternate code path. If it's a sanity check, if the method does nothing when the condition fails, then i want to know that from the start. I mean, just think about it - if you were asking me the question aloud, "Shog, what happens if btn is null?" - and i replied, "well, CG, if it isn't null, then we change the text and the color and attach a little icon which we load from resources, and if the user is logged in then we enable it but otherwise we disable it and set up a tool tip with a little message explaining that they have to log in, and"... at this point, you should have already hit me upside the head with a 2x4, having had plenty of time to go out and buy a 2x4 while i was busy reading off the novella that was the tooltip text... My point here is that you wouldn't put up with that sort of madness in any other medium, so why allow it in code? Also, i hate excessive indentation.

                              every night, i kneel at the foot of my bed and thank the Great Overseeing Politicians for protecting my freedoms by reducing their number, as if they were deer in a state park. -- Chris Losinger, Online Poker Players?

                              K Offline
                              K Offline
                              Kevin McFarlane
                              wrote on last edited by
                              #31

                              Shog9 wrote:

                              i hate excessive indentation.

                              Me too. Though if methods are as short as good style says they should be there should not be an excuse for excessive indentation.

                              Kevin

                              1 Reply Last reply
                              0
                              • C Christian Graus

                                As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

                                Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

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

                                If the function is relatively short (will fit on my screen without scrolling) I go with option 1. If it's longer, I go with option 2. I don't mind a lot of indentation as long as the code is formatted appropriately and there's a dearth of comments. Also, if a function does exceed the height of my screen, I try to find ways to abstract some the functionality into smaller re-usable functions. Some of the code I've had to maintain over the last three years had functions in it that exceeded 500 lines, and some files exceeded 6000 lines. Those were a pain in the ass to debug.

                                "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

                                K P 2 Replies Last reply
                                0
                                • C Christian Graus

                                  As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

                                  Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

                                  S Offline
                                  S Offline
                                  Sam_c
                                  wrote on last edited by
                                  #33

                                  i go with second one as i find it easier and makes more sence to me. if(btn == null) return; i have the return on a second line.

                                  Code Project Lounge 101 by John Cardinal :beer::bob::beer:

                                  1 Reply Last reply
                                  0
                                  • realJSOPR realJSOP

                                    If the function is relatively short (will fit on my screen without scrolling) I go with option 1. If it's longer, I go with option 2. I don't mind a lot of indentation as long as the code is formatted appropriately and there's a dearth of comments. Also, if a function does exceed the height of my screen, I try to find ways to abstract some the functionality into smaller re-usable functions. Some of the code I've had to maintain over the last three years had functions in it that exceeded 500 lines, and some files exceeded 6000 lines. Those were a pain in the ass to debug.

                                    "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

                                    K Offline
                                    K Offline
                                    Kevin McFarlane
                                    wrote on last edited by
                                    #34

                                    John Simmons / outlaw programmer wrote:

                                    Some of the code I've had to maintain over the last three years had functions in it that exceeded 500 lines, and some files exceeded 6000 lines. Those were a pain in the ass to debug.

                                    Tell me about it! :mad:

                                    Kevin

                                    W 1 Reply Last reply
                                    0
                                    • K Kevin McFarlane

                                      John Simmons / outlaw programmer wrote:

                                      Some of the code I've had to maintain over the last three years had functions in it that exceeded 500 lines, and some files exceeded 6000 lines. Those were a pain in the ass to debug.

                                      Tell me about it! :mad:

                                      Kevin

                                      W Offline
                                      W Offline
                                      WillemM
                                      wrote on last edited by
                                      #35

                                      Yup, that sucks... It's the main reason why I love short methods and partial classes in .NET

                                      WM. What about weapons of mass-construction? "What? Its an Apple MacBook Pro. They are sexy!" - Paul Watson My blog

                                      1 Reply Last reply
                                      0
                                      • realJSOPR realJSOP

                                        If the function is relatively short (will fit on my screen without scrolling) I go with option 1. If it's longer, I go with option 2. I don't mind a lot of indentation as long as the code is formatted appropriately and there's a dearth of comments. Also, if a function does exceed the height of my screen, I try to find ways to abstract some the functionality into smaller re-usable functions. Some of the code I've had to maintain over the last three years had functions in it that exceeded 500 lines, and some files exceeded 6000 lines. Those were a pain in the ass to debug.

                                        "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

                                        P Offline
                                        P Offline
                                        Paul Conrad
                                        wrote on last edited by
                                        #36

                                        John Simmons / outlaw programmer wrote:

                                        Some of the code I've had to maintain over the last three years had functions in it that exceeded 500 lines, and some files exceeded 6000 lines.

                                        That is way too excessive. Gotta stick to it being able to fit on the screen all at once. Hope the original coder doesn't work there anymore...

                                        "The clue train passed his station without stopping." - John Simmons / outlaw programmer

                                        realJSOPR 1 Reply Last reply
                                        0
                                        • C Christian Graus

                                          As a rule, I like to have one exit point for functions, but I sometimes make an exception for initial state checks. Which do you prefer Button btn = sender as Button; if (btn != null) { } OR Button btn = sender as Button; if (btn == null) return;

                                          Christian Graus - Microsoft MVP - C++ "I am working on a project that will convert a FORTRAN code to corresponding C++ code.I am not aware of FORTRAN syntax" ( spotted in the C++/CLI forum )

                                          P Offline
                                          P Offline
                                          PIEBALDconsult
                                          wrote on last edited by
                                          #37

                                          The first, always. Though of course I'd probably use is rather than as.

                                          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