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. A question of indentation!

A question of indentation!

Scheduled Pinned Locked Moved The Lounge
questionc++helptutorial
81 Posts 23 Posters 36 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.
  • N Nish Nishant

    Indentation is nice. In fact code that is not indented is an absolute pain to even look at. But then sometimes you get into absurd levels of indentation. Right now I am working with the PGP SDK. For certain operations I need to call about 7-10 functions sequentially. The problem is that each of these functions can be called ONLY if all the previous functions are successful. Thus I have something like this.

    if(call1())
    {
    if(call2())
    {
    if(call3())
    {
    if(call4())
    {
    if((call5())
    {
    if(call6())
    {

    That's just a sample, just the tip of the large iceberg. Often it get's a LOT more deeply nested than I have shown above! In such situations can we actually do away with indentation at least partially? For example would it be considered okay to do this.

    if(call1())
    {
    if(call2())
    {
    if(call3())
    {
    if(call4())
    {
    if((call5())
    {
    if(call6())
    {

    I have maintained a little indentation, but it's not perfectly done! Your comments are welcome


    Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

    J Offline
    J Offline
    Jason Hooper
    wrote on last edited by
    #50

    Nish - Native CPian wrote: In fact code that is not indented is an absolute pain to even look at. But then sometimes you get into absurd levels of indentation Try generating HTML tables with perl's CGI.pm. (Yes I'm using the MDE to edit perl files... this was before I learned vi) - Jason (SonorkID 100.611) In the beginning, teachers taught the 5 W's: who, what, where, when, why. Now it's just a big damn G

    1 Reply Last reply
    0
    • E Eddie Velasquez

      Yeah I thought about this but I think it's a bad idea. Check out my reasons why this use of exceptions is a bad idea post


      Eddie Velasquez: A Squeezed Devil
      Checkout General Guidelines for C# Class Implementation

      T Offline
      T Offline
      Tomasz Sowinski
      wrote on last edited by
      #51

      I don't buy performance-related arguments, at least not in 100%. While there are the situations in which this could matter (thight loops etc), in my example you'd access disk. For sure this operation would be orders of magnitude slower than throwing/catching exceptions. The same applies to displaying anything on the screen or accepting user input. In short, the cost associated with exception handling would be totally invisible. Tomasz Sowinski -- http://www.shooltz.com

      - It's for protection
      - Protection from what? Zee Germans?

      E 1 Reply Last reply
      0
      • J Jason Gerard

        Nish - Native CPian wrote: PGP calls return a PGPError and you need to call IsPGPError(...) on it to figure out whether it was an error or not. That is the worst API I've ever heard of. Jason Gerard

        A Offline
        A Offline
        Andreas Saurwein
        wrote on last edited by
        #52

        Jason Gerard wrote: That is the worst API I've ever heard of Try Windows ;) ERROR_MORE_DATA Well, actually you have the same kind of return values in almost any API - commonly you find this things in "evolved" API's where conditions changed but not the environment. Thus, the function returns a error which must be interpreted to find out that its actually just a information. Sometimes its just a misconception as for ERROR_MORE_DATA. Vote against software patents in europe

        1 Reply Last reply
        0
        • C Chris Maunder

          do {
          if (!call1())
          break;
          if (!call2())
          break;
          ...
          } while (false);

          Cleanup();

          cheers, Chris Maunder

          VC++ - the language that doesn't say 'no'

          T Offline
          T Offline
          Tomasz Sowinski
          wrote on last edited by
          #53

          What about this? :)

          switch (1)
          {
          case 1: if (!call1()) break;
          case 2: if (!call2()) break;
          case 3: if (!call3()) break;
          ...
          }

          Tomasz Sowinski -- http://www.shooltz.com

          - It's for protection
          - Protection from what? Zee Germans?

          N 1 Reply Last reply
          0
          • E Eddie Velasquez

            (Using my best Yoda voice...) Ummm. Strong in the force you are... but OOP you must.;)


            Eddie Velasquez: A Squeezed Devil
            Checkout General Guidelines for C# Class Implementation

            N Offline
            N Offline
            Nish Nishant
            wrote on last edited by
            #54

            Eddie Velasquez wrote: but OOP you must. Yeah. I am gonna OOP more from now on ... Nish :-)


            Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

            1 Reply Last reply
            0
            • C Chris Maunder

              do {
              if (!call1())
              break;
              if (!call2())
              break;
              ...
              } while (false);

              Cleanup();

              cheers, Chris Maunder

              VC++ - the language that doesn't say 'no'

              N Offline
              N Offline
              Nish Nishant
              wrote on last edited by
              #55

              Thanks Chris M. PeterChen had already suggested this to me. Though he used a 0 instead of a false as you did :-) By the way your do while brace-poitioning is ugly Dont use do { like a java guy. Put it as do { like a C++ guy Nish


              Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

              1 Reply Last reply
              0
              • T Tomasz Sowinski

                What about this? :)

                switch (1)
                {
                case 1: if (!call1()) break;
                case 2: if (!call2()) break;
                case 3: if (!call3()) break;
                ...
                }

                Tomasz Sowinski -- http://www.shooltz.com

                - It's for protection
                - Protection from what? Zee Germans?

                N Offline
                N Offline
                Nish Nishant
                wrote on last edited by
                #56

                That was indeed innovative Tomasz :-) Nish


                Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                1 Reply Last reply
                0
                • T Tomasz Sowinski

                  I don't buy performance-related arguments, at least not in 100%. While there are the situations in which this could matter (thight loops etc), in my example you'd access disk. For sure this operation would be orders of magnitude slower than throwing/catching exceptions. The same applies to displaying anything on the screen or accepting user input. In short, the cost associated with exception handling would be totally invisible. Tomasz Sowinski -- http://www.shooltz.com

                  - It's for protection
                  - Protection from what? Zee Germans?

                  E Offline
                  E Offline
                  Eddie Velasquez
                  wrote on last edited by
                  #57

                  Tomasz Sowinski wrote: While there are the situations in which this could matter (thight loops etc), in my example you'd access disk As everything in software development there's no such thing as an absolute certainty. That's why I used the word "usually". And I still believe it's a bad idea to getting used to use exceptions for other things besides error handling. Tomasz Sowinski wrote: In short, the cost associated with exception handling would be totally invisible. Remember the cost of exceptions isn't only related to speed, size matters too! (Doesn't matter what some women say :-O ;))


                  Eddie Velasquez: A Squeezed Devil
                  Checkout General Guidelines for C# Class Implementation

                  T 1 Reply Last reply
                  0
                  • T Tomasz Sowinski

                    Post more code - especially, how PGPError is returned and when it means an error. Tomasz Sowinski -- http://www.shooltz.com

                    - It's for protection
                    - Protection from what? Zee Germans?

                    N Offline
                    N Offline
                    Nish Nishant
                    wrote on last edited by
                    #58

                    Tomasz Sowinski wrote: Post more code Tomasz Sowinski said that on the Lounge ;-) ;-) Nish


                    Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                    T 1 Reply Last reply
                    0
                    • J James Pullicino

                      Nish - Native CPian wrote: Shucks! It always comes down to the basics and theory. If my OOP theory was strong enough I'd not have run into this situation Nish, don't get discouraged. The prime motivation for most of us to learn OOP was because of these things. Don't shy away from OOP. In a few months you will be the one telling others to wrap their functions into objects. C++ Programmers do it in class Drinking In The Sun Forgot Password?

                      N Offline
                      N Offline
                      Nish Nishant
                      wrote on last edited by
                      #59

                      [James Pullicino] wrote: Nish, don't get discouraged. The prime motivation for most of us to learn OOP was because of these things. Don't shy away from OOP. In a few months you will be the one telling others to wrap their functions into objects. Thanks James! :-) Nish


                      Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                      1 Reply Last reply
                      0
                      • N Navin

                        Nish - Native CPian wrote: if (call1() && call2() && call3() ....) That won;'t work. I am not supposed to call call-n unless call-n-1 returns true! :confused: Why won't that work then? With C++, you have "short-circuit" evaluation - that is, if the first item in an If statement fails, the rest won't even get evaluated. For instance, I have code like this all the time (well, when I'm not using CStrings... :-D) : if(pStr != NULL && strlen(pStr) > 0) { ... } If pStr is NULL, the first condition fails, and the second condition (strlen) won't even be evaluated. No generalization is 100% true. Not even this one.

                        N Offline
                        N Offline
                        Nish Nishant
                        wrote on last edited by
                        #60

                        Navin wrote: If pStr is NULL, the first condition fails, and the second condition (strlen) won't even be evaluated. PGP calls don't return true/false/1/0. They return a PGPError type. We gotta call IsPGPError() on the return value to figure out if it's an error. On some occasions an error is permissible. Like if we have a call that works only with DSS keys, then if it fails for an RSA key it's not really an error. Nish


                        Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                        1 Reply Last reply
                        0
                        • N Nish Nishant

                          Eddie Velasquez wrote: if(!call3()) return; I can't do that. Since I need to do some cleaning up as well :( Nish


                          Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

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

                          Some people use goto :~ for this kind of stuff. Basically it works something like this:

                          if(someCondition) {
                             // acquire some resources...
                             // some error is detected - bail out
                             goto cleanup\_1;
                          }
                          
                          if(someOtherCondition) {
                             // acquire some more resources...
                             // some error is detected - bail out
                             goto cleanup\_2;
                          } 
                          
                          // perhaps some more code
                          
                          return true; // for success
                          

                          cleanup_2:
                          // cleanup resources acquired up to "goto cleanup_2"
                          cleanup_1:
                          // cleanup resources acquired up to "goto cleanup_1"
                          return false; // for failure

                          This is the only instance where I'm prepared to defend the usage of goto's. It's fast (no exception handling overhead), it's not spaghetti code and it's quite readable! Sonorked as well: 100.13197 jorgen FreeBSD is sexy.

                          1 Reply Last reply
                          0
                          • E Eddie Velasquez

                            Tomasz Sowinski wrote: While there are the situations in which this could matter (thight loops etc), in my example you'd access disk As everything in software development there's no such thing as an absolute certainty. That's why I used the word "usually". And I still believe it's a bad idea to getting used to use exceptions for other things besides error handling. Tomasz Sowinski wrote: In short, the cost associated with exception handling would be totally invisible. Remember the cost of exceptions isn't only related to speed, size matters too! (Doesn't matter what some women say :-O ;))


                            Eddie Velasquez: A Squeezed Devil
                            Checkout General Guidelines for C# Class Implementation

                            T Offline
                            T Offline
                            Tomasz Sowinski
                            wrote on last edited by
                            #62

                            Eddie Velasquez wrote: Remember the cost of exceptions isn't only related to speed, size matters too! So how much bigger my program will be if I replace multiple nested ifs with try/throw/catch? Assuming that you're using exceptions to catch 'real' errors the difference is zero. Tomasz Sowinski -- http://www.shooltz.com

                            - It's for protection
                            - Protection from what? Zee Germans?

                            E 1 Reply Last reply
                            0
                            • N Nish Nishant

                              peterchen wrote: do { // while(0) ok = hamlet(); if (!ok) break; ok = ophelia(); if (!ok) break; ....} while(0); Cool! I like your do while(0) idea. That's what I am gonna use I think :-) Nish


                              Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

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

                              Nish - Native CPian wrote: I like your do while(0) idea do { } while(0) is a really cool technique, especially with macros. It is easy to mistype macros in such ways that they look syntactically correct, but expanded they wreak havoc. Consider this:

                              #define RET_IF_FAIL(x) if(FAILED(x)) return

                              if(someCondition)
                              RET_IF_FAIL(m_pObject->DoTheChokaChoka());
                              else
                              MessageBox(NULL, "someCondition not met", "Status report", MB_OK);

                              The else will be connected to your "hidden if" inside RET_IF_FAIL which is clearly not the intent. The expanded code will look like:

                              if(someCondition)
                              if(FAILED(m_pObject->DoTheChokaChoka())) return;
                              else
                              MessageBox(NULL, "someCondition not met", "Status report", MB_OK);

                              Scary stuff! I've had my fair share of these bloody mistakes! Solution? Keep on reading:

                              #define RET_IF_FAIL(x) do { if(FAILED(hr)) return; } while(0)
                              if(someCondition)
                              RET_IF_FAIL(pObject->DoTheChokaChoka());
                              else
                              MessageBox(NULL, "someCondition not met", "Status report", MB_OK);

                              This is much better since the "hidden if" is wrapped inside a block which has an associated language construct - the do while. Thus the if nor the block cannot be "misconnected". The expanded code will be:

                              if(someCondition)
                              do { if(FAILED(m_pObject->DoTheChokaChoka())) return; } while(0);
                              else
                              MessageBox(NULL, "someCondition not met", "Status report", MB_OK);

                              And the best part is that a do { } while(0) is totally costless! The compiler will optimize away the loop expression/jump so that it will not add any extra garbage to your code. Sonorked as well: 100.13197 jorgen FreeBSD is sexy.

                              1 Reply Last reply
                              0
                              • T Tomasz Sowinski

                                Eddie Velasquez wrote: Remember the cost of exceptions isn't only related to speed, size matters too! So how much bigger my program will be if I replace multiple nested ifs with try/throw/catch? Assuming that you're using exceptions to catch 'real' errors the difference is zero. Tomasz Sowinski -- http://www.shooltz.com

                                - It's for protection
                                - Protection from what? Zee Germans?

                                E Offline
                                E Offline
                                Eddie Velasquez
                                wrote on last edited by
                                #64

                                Tomasz Sowinski wrote: So how much bigger my program will be if I replace multiple nested ifs with try/throw/catch? Assuming that you're using exceptions to catch 'real' errors the difference is zero. It depends. A lot of factors come into play, obvious ones: if you define variables with ctors and dtors between the ifs and if the code is templated. As I said before: it all depends on the particular case. In some scenarios even the use of exceptions for error reporting is overkill. For most developers getting into the habit of misusing exceptions (or templates or whatever relatively obscure language feature) makes them produce bad code. I'm not saying that you or me will produce buggy or bad code (we don't write buggy code, do we? ;) ) But the average developer is so lame that (s)he acts like a robot without really thinking about the code (s)he is writing and the consecuences of the design decisions made.


                                Eddie Velasquez: A Squeezed Devil
                                Checkout General Guidelines for C# Class Implementation

                                T 1 Reply Last reply
                                0
                                • E Eddie Velasquez

                                  Tomasz Sowinski wrote: So how much bigger my program will be if I replace multiple nested ifs with try/throw/catch? Assuming that you're using exceptions to catch 'real' errors the difference is zero. It depends. A lot of factors come into play, obvious ones: if you define variables with ctors and dtors between the ifs and if the code is templated. As I said before: it all depends on the particular case. In some scenarios even the use of exceptions for error reporting is overkill. For most developers getting into the habit of misusing exceptions (or templates or whatever relatively obscure language feature) makes them produce bad code. I'm not saying that you or me will produce buggy or bad code (we don't write buggy code, do we? ;) ) But the average developer is so lame that (s)he acts like a robot without really thinking about the code (s)he is writing and the consecuences of the design decisions made.


                                  Eddie Velasquez: A Squeezed Devil
                                  Checkout General Guidelines for C# Class Implementation

                                  T Offline
                                  T Offline
                                  Tomasz Sowinski
                                  wrote on last edited by
                                  #65

                                  Eddie Velasquez wrote: In some scenarios even the use of exceptions for error reporting is overkill. Hard real time systems controlling nuclear reactors, yes. But not for majority of non-embedded stuff. Anyway, Standard C++ uses exceptions for basic functionality, like reporting failures from new operator. Your code already has exception frames set. Eddie Velasquez wrote: But the average developer is so lame that (s)he acts like a robot without really thinking about the code (s)he is writing and the consecuences of the design decisions made. So it's better to have dozen of nested ifs and 'manual' cleanup code? C'mon :) Tomasz Sowinski -- http://www.shooltz.com

                                  - It's for protection
                                  - Protection from what? Zee Germans?

                                  E 1 Reply Last reply
                                  0
                                  • T Tomasz Sowinski

                                    Eddie Velasquez wrote: In some scenarios even the use of exceptions for error reporting is overkill. Hard real time systems controlling nuclear reactors, yes. But not for majority of non-embedded stuff. Anyway, Standard C++ uses exceptions for basic functionality, like reporting failures from new operator. Your code already has exception frames set. Eddie Velasquez wrote: But the average developer is so lame that (s)he acts like a robot without really thinking about the code (s)he is writing and the consecuences of the design decisions made. So it's better to have dozen of nested ifs and 'manual' cleanup code? C'mon :) Tomasz Sowinski -- http://www.shooltz.com

                                    - It's for protection
                                    - Protection from what? Zee Germans?

                                    E Offline
                                    E Offline
                                    Eddie Velasquez
                                    wrote on last edited by
                                    #66

                                    Tomasz Sowinski wrote: Hard real time systems controlling nuclear reactors, yes. No need for exageration. Tomasz Sowinski wrote: Standard C++ uses exceptions for basic functionality, like reporting failures from new operator. Not Visual Studio. At least version 6.0 Tomasz Sowinski wrote: So it's better to have dozen of nested ifs and 'manual' cleanup code? C'mon More exageration. When a function is overly complex you split it in managable units. Destructors were invented for cleanup. Why did you quote the word 'manual'? I don't recall mentioning manual cleanup code. :confused: I've never advocated writing spagetti code or not using exceptions or templates or whatever in my code. Just use 'em where they should be used and try hard not to grow bad habits.


                                    Eddie Velasquez: A Squeezed Devil
                                    Checkout General Guidelines for C# Class Implementation

                                    T 1 Reply Last reply
                                    0
                                    • N Nish Nishant

                                      Indentation is nice. In fact code that is not indented is an absolute pain to even look at. But then sometimes you get into absurd levels of indentation. Right now I am working with the PGP SDK. For certain operations I need to call about 7-10 functions sequentially. The problem is that each of these functions can be called ONLY if all the previous functions are successful. Thus I have something like this.

                                      if(call1())
                                      {
                                      if(call2())
                                      {
                                      if(call3())
                                      {
                                      if(call4())
                                      {
                                      if((call5())
                                      {
                                      if(call6())
                                      {

                                      That's just a sample, just the tip of the large iceberg. Often it get's a LOT more deeply nested than I have shown above! In such situations can we actually do away with indentation at least partially? For example would it be considered okay to do this.

                                      if(call1())
                                      {
                                      if(call2())
                                      {
                                      if(call3())
                                      {
                                      if(call4())
                                      {
                                      if((call5())
                                      {
                                      if(call6())
                                      {

                                      I have maintained a little indentation, but it's not perfectly done! Your comments are welcome


                                      Regards, Nish Native CPian. Born and brought up on CP. With the CP blood in him.

                                      R Offline
                                      R Offline
                                      Ravi Bhavnani
                                      wrote on last edited by
                                      #67

                                      How about:

                                      if (call1() && call2() && call3() &&
                                      call4() && call5() && call6()) {
                                      // Success
                                      } else {
                                      // Error
                                      }

                                      /ravi "There is always one more bug..." http://www.ravib.com ravib@ravib.com

                                      A 1 Reply Last reply
                                      0
                                      • E Eddie Velasquez

                                        Tomasz Sowinski wrote: Hard real time systems controlling nuclear reactors, yes. No need for exageration. Tomasz Sowinski wrote: Standard C++ uses exceptions for basic functionality, like reporting failures from new operator. Not Visual Studio. At least version 6.0 Tomasz Sowinski wrote: So it's better to have dozen of nested ifs and 'manual' cleanup code? C'mon More exageration. When a function is overly complex you split it in managable units. Destructors were invented for cleanup. Why did you quote the word 'manual'? I don't recall mentioning manual cleanup code. :confused: I've never advocated writing spagetti code or not using exceptions or templates or whatever in my code. Just use 'em where they should be used and try hard not to grow bad habits.


                                        Eddie Velasquez: A Squeezed Devil
                                        Checkout General Guidelines for C# Class Implementation

                                        T Offline
                                        T Offline
                                        Tomasz Sowinski
                                        wrote on last edited by
                                        #68

                                        Eddie Velasquez wrote: Not Visual Studio. At least version 6.0 What's the importance of this? :-D Eddie Velasquez wrote: More exageration. Just a little bit :) Anyway, we're not going to agree. Let's finish this discussion. Tomasz Sowinski -- http://www.shooltz.com

                                        - It's for protection
                                        - Protection from what? Zee Germans?

                                        E 1 Reply Last reply
                                        0
                                        • T Tomasz Sowinski

                                          Eddie Velasquez wrote: Not Visual Studio. At least version 6.0 What's the importance of this? :-D Eddie Velasquez wrote: More exageration. Just a little bit :) Anyway, we're not going to agree. Let's finish this discussion. Tomasz Sowinski -- http://www.shooltz.com

                                          - It's for protection
                                          - Protection from what? Zee Germans?

                                          E Offline
                                          E Offline
                                          Eddie Velasquez
                                          wrote on last edited by
                                          #69

                                          Tomasz Sowinski wrote: What's the importance of this? Well, a lot of developers use it as it's main compiler? And the some big chunks of the standard aren't correctly handled by VC6 (and VC7). And that you implied (or so I interpreted) that because standard C++ uses exceptions all over the place then everybody is using exceptions unknowingly, so the exception overhead has already been payed for. And I said that VC6 doesn't conform very well so the exception overhead isn't automatically included. Tomasz Sowinski wrote: Anyway, we're not going to agree. Let's finish this discussion. That's ok with me.


                                          Eddie Velasquez: A Squeezed Devil
                                          Checkout General Guidelines for C# Class Implementation

                                          T 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