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. if else Style

if else Style

Scheduled Pinned Locked Moved The Lounge
tutorial
79 Posts 33 Posters 5 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.
  • T trønderen

    Similarly, "if the door is locked" perform the same function as "if the door is locked is true". In speech, noone that I know of includes the "is true". So why do you program as

    if (doorIsLocked == true) ...

    rather than

    if (doorIsLocked) ...

    I see no reason for or advantage of creating a more complex logical expression, adding a second, redundant element. Both "doorIsLocked" and "doorIsLocked == true" are logical expressions, the second one just more complex than it needs to be. (Hopefully, the compiler is able to optimize the redundant element away!) If I program a test like

    if (x < 10 && x < 20) ...

    all programmers I know would point out that it is redundant to test for "x < 20" if you already have tested that x < 10. Adding an extra element a logical expression, to see whether a true "a" is equal to "true" (or that a false "a" is different from "true") is similarly redundant. The logical "a" expression is true or false, all by itself!

    Religious freedom is the freedom to say that two plus two make five.

    J Offline
    J Offline
    jschell
    wrote on last edited by
    #34

    Just noting that the semantics of how a logical expression is resolved in C++ is different than in C#/Java. So the following is valid in C/C++

    int v = 0;
    if (v) {}
    else {}

    Because of operator overloading in C++ (to be fair it has been long time since I did this) I believe there can be situations where one must explicitly use the following. Leaving it out at a minimum might lead to a compiler error. I can't visualize a case where it would not lead to a compiler error but might be one and then it would lead to a different and incorrect result at least compared to the code below.

    if (p == true) ...

    1 Reply Last reply
    0
    • Sander RosselS Sander Rossel

      if (expression)
      {

      }
      else
      {

      }

      Everything else is just unnecessary typing/reading.

      Best, Sander Azure DevOps Succinctly (free eBook) Azure Serverless Succinctly (free eBook) Migrating Apps to the Cloud with Azure arrgh.js - Bringing LINQ to JavaScript

      K Offline
      K Offline
      k5054
      wrote on last edited by
      #35

      I like things more compact

      if ( expression ) {

      } else {

      }

      I think that's the way it's done in K&R, in which case I'm in good company. But putting the opening brace on the first line of a function definition annoys me intensely e.g. Don't:

      int main(int argc, char *argv[]) { /* <== No! brace goes on next line!!!
      }

      "A little song, a little dance, a little seltzer down your pants" Chuckles the clown

      C 1 Reply Last reply
      0
      • B BernardIE5317

        Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

        Mircea NeacsuM Offline
        Mircea NeacsuM Offline
        Mircea Neacsu
        wrote on last edited by
        #36

        As @GregUtas was pointing out, a lot of answers for a (bad) style question! So, I'll just add my own, just to increase the noise :) First, although the OP doesn't specify, we have to assume that the code is C++, because it looks like it and in plain C true and false are not defined. Now, if it's C++, both styles are wrong as @sanderrossel pointed out. The extra fluff of "== true" or "== false" only adds space for confusion and potential errors like the program below illustrates.

        #include

        int main()
        {
        int one = 1, two = 2;

        if (one + two == true) {
        printf("Miracle of miracles!\n");
        } else if (one + two == false) {
        printf("Another miracle!!\n");
        } else {
        printf("1+2 = 3, you moron!\n");
        }

        return 0;
        }

        It compiles fine with just a warning about "unsafe mix of type 'int' and type 'bool' in operation". Unsafe indeed! PS Assume a joker comes along and added to a header file:

        #define true 3

        Mircea

        1 Reply Last reply
        0
        • B BernardIE5317

          Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

          honey the codewitchH Online
          honey the codewitchH Online
          honey the codewitch
          wrote on last edited by
          #37

          My personal opinion is that more typing leads to more bugs, so there needs to be a compelling reason in terms of the code expressing intent in order to add redundancy to it, which is what you're doing here. I mean, it's probably somewhat subjective, but I don't find much value in your else with the additional test. If anything it's sort of jarring to me, because just skimming it I would automatically think you're doing something "off book" so to speak with that else if, and I'd have to look at it twice to be sure what I was looking at. I don't like that. So overall I prefer just the else in the buff, at least in the situation you presented.

          Check out my IoT graphics library here: https://honeythecodewitch.com/gfx And my IoT UI/User Experience library here: https://honeythecodewitch.com/uix

          0 T 2 Replies Last reply
          0
          • honey the codewitchH honey the codewitch

            My personal opinion is that more typing leads to more bugs, so there needs to be a compelling reason in terms of the code expressing intent in order to add redundancy to it, which is what you're doing here. I mean, it's probably somewhat subjective, but I don't find much value in your else with the additional test. If anything it's sort of jarring to me, because just skimming it I would automatically think you're doing something "off book" so to speak with that else if, and I'd have to look at it twice to be sure what I was looking at. I don't like that. So overall I prefer just the else in the buff, at least in the situation you presented.

            Check out my IoT graphics library here: https://honeythecodewitch.com/gfx And my IoT UI/User Experience library here: https://honeythecodewitch.com/uix

            0 Offline
            0 Offline
            0x01AA
            wrote on last edited by
            #38

            Do I understand you correclty? Do you mean somthing like ...

            if((expression == true) == true) {...}

            ... is overkill? ;P

            1 Reply Last reply
            0
            • 0 0x01AA

              But you don't really mean something like?

              if (expression)
              {
              }
              else if (!expression)
              {
              }
              else
              {
              throw(this and that);
              }

              honey the codewitchH Online
              honey the codewitchH Online
              honey the codewitch
              wrote on last edited by
              #39

              I will fite you over that code. :mad:

              Check out my IoT graphics library here: https://honeythecodewitch.com/gfx And my IoT UI/User Experience library here: https://honeythecodewitch.com/uix

              1 Reply Last reply
              0
              • T trønderen

                Agree. 8 lines is required, even for cases that could have used a simple ?:, but beyond 8 lines is a waste. Many times I have met programmers who really oppose ?: and insist that e.g.

                ticketClass = (age >= 16)? adult : child;

                must be written over 8 lines as

                if (age >= 16)
                {
                ticketClass = adult;
                }
                else
                {
                ticketClass = child;
                }

                If their productivity is measured in number of source code lines produced, I can see the justification for it, but that's all I can think of :-) Another funny thing is that those who oppose ?: frequently are proud of their creations in regular expressions.

                Religious freedom is the freedom to say that two plus two make five.

                honey the codewitchH Online
                honey the codewitchH Online
                honey the codewitch
                wrote on last edited by
                #40

                I think the ternary operator gets a bad rap (although somewhat deserved) because it so often gets abused, particularly, I think, because it's so easy to abuse. Just today I caught myself chaining 3 of them together, and then luckily confused myself and rewrote it using if statements. :laugh:

                Check out my IoT graphics library here: https://honeythecodewitch.com/gfx And my IoT UI/User Experience library here: https://honeythecodewitch.com/uix

                1 Reply Last reply
                0
                • honey the codewitchH honey the codewitch

                  My personal opinion is that more typing leads to more bugs, so there needs to be a compelling reason in terms of the code expressing intent in order to add redundancy to it, which is what you're doing here. I mean, it's probably somewhat subjective, but I don't find much value in your else with the additional test. If anything it's sort of jarring to me, because just skimming it I would automatically think you're doing something "off book" so to speak with that else if, and I'd have to look at it twice to be sure what I was looking at. I don't like that. So overall I prefer just the else in the buff, at least in the situation you presented.

                  Check out my IoT graphics library here: https://honeythecodewitch.com/gfx And my IoT UI/User Experience library here: https://honeythecodewitch.com/uix

                  T Offline
                  T Offline
                  trønderen
                  wrote on last edited by
                  #41

                  honey the codewitch wrote:

                  My personal opinion is that more typing leads to more bugs

                  So, APL is the answer :-)

                  Religious freedom is the freedom to say that two plus two make five.

                  1 Reply Last reply
                  0
                  • B BernardIE5317

                    Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

                    0 Offline
                    0 Offline
                    0x01AA
                    wrote on last edited by
                    #42

                    For the discussion about '== true' and '== false' read this, it is worth the time: Boolean algebra - Wikipedia[^] After get it all you will see among others why a.) a boolean is either true or false and nothing other! b.) 'A AND B' is the same like 'NOT(NOT A OR NOT B)' and also e.g. why 'A OR B' is the same like 'NOT(NOT A AND NOT B)'

                    1 Reply Last reply
                    0
                    • K k5054

                      I like things more compact

                      if ( expression ) {

                      } else {

                      }

                      I think that's the way it's done in K&R, in which case I'm in good company. But putting the opening brace on the first line of a function definition annoys me intensely e.g. Don't:

                      int main(int argc, char *argv[]) { /* <== No! brace goes on next line!!!
                      }

                      "A little song, a little dance, a little seltzer down your pants" Chuckles the clown

                      C Offline
                      C Offline
                      charlieg
                      wrote on last edited by
                      #43

                      yeah, the brace on the same line makes me want to puke.

                      Charlie Gilley “They who can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.” BF, 1759 Has never been more appropriate.

                      T N 2 Replies Last reply
                      0
                      • C charlieg

                        yeah, the brace on the same line makes me want to puke.

                        Charlie Gilley “They who can give up essential liberty to obtain a little temporary safety deserve neither liberty nor safety.” BF, 1759 Has never been more appropriate.

                        T Offline
                        T Offline
                        trønderen
                        wrote on last edited by
                        #44

                        charlieg wrote:

                        yeah, the brace on the same line makes me want to puke.

                        I follow the same rule when I write plain prose. If I want to write something that is not absolute but associated with some condition, I enclose the entire conditional part in braces and put on separate lines. Such as

                        If (the rain stops), I told her,
                        {
                        let's take a walk in the park.
                        }
                        but if it keeps raining,
                        {
                        I want to lit the fireplace and fetch a bottle of wine from the basement
                        }

                        When I write the prose this way, it is so much easier for the reader to foollow the structure of both the conversation and the actions.

                        Religious freedom is the freedom to say that two plus two make five.

                        C 1 Reply Last reply
                        0
                        • B BernardIE5317

                          Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

                          G Offline
                          G Offline
                          Gary R Wheeler
                          wrote on last edited by
                          #45

                          Great Ghu NO! 1st style is fine. Everyone understands the else keyword. 2nd style is absolutely ripe for unintended bugs. You change the expression in the if () and then forget to make the corresponding change in the else if(). In both cases checking "== true" is a code smell (you don't understand logical expressions) and redundant. Checking "== false" is misleading and an easy source of errors.

                          Software Zen: delete this;

                          B 1 Reply Last reply
                          0
                          • G Gary R Wheeler

                            Great Ghu NO! 1st style is fine. Everyone understands the else keyword. 2nd style is absolutely ripe for unintended bugs. You change the expression in the if () and then forget to make the corresponding change in the else if(). In both cases checking "== true" is a code smell (you don't understand logical expressions) and redundant. Checking "== false" is misleading and an easy source of errors.

                            Software Zen: delete this;

                            B Offline
                            B Offline
                            BernardIE5317
                            wrote on last edited by
                            #46

                            re/ ==true/false To finally set the record straight I do not write that way. I write if(expression) and if(!expression). I am not certain why I stuck the == true/false in the specimen. Perhaps to save readers the trouble of looking for the negation ! operator. re/ 1st 2nd styles sometimes I favor the self documenting of the 2nd style for lengthy complex conditions except for the unintended consequence of compiler warnings stating not all paths return a value. So for that reason alone I will probably insist on 1st style. re/ risking unintended bugs I am not worried as I am confident of being sufficiently careful also I do not expect the relevant code to require re-write. Though this is moot per above.

                            1 Reply Last reply
                            0
                            • T trønderen

                              Agree. 8 lines is required, even for cases that could have used a simple ?:, but beyond 8 lines is a waste. Many times I have met programmers who really oppose ?: and insist that e.g.

                              ticketClass = (age >= 16)? adult : child;

                              must be written over 8 lines as

                              if (age >= 16)
                              {
                              ticketClass = adult;
                              }
                              else
                              {
                              ticketClass = child;
                              }

                              If their productivity is measured in number of source code lines produced, I can see the justification for it, but that's all I can think of :-) Another funny thing is that those who oppose ?: frequently are proud of their creations in regular expressions.

                              Religious freedom is the freedom to say that two plus two make five.

                              Graeme_GrantG Offline
                              Graeme_GrantG Offline
                              Graeme_Grant
                              wrote on last edited by
                              #47

                              you forgot one...

                              ticketClass = age switch
                              {
                              >= 16 => adult,
                              _ => child
                              };

                              Graeme


                              "I fear not the man who has practiced ten thousand kicks one time, but I fear the man that has practiced one kick ten thousand times!" - Bruce Lee

                              “I fear not the man who has practised 10,000 kicks once, but I fear the man who has practised one kick 10,000 times.” - Bruce Lee.

                              1 Reply Last reply
                              0
                              • B BernardIE5317

                                Greetings & Kind Regards I seek advice and knowledge of others' practice re/ a minor matter of style. In particular to be specific I vacillate betwixt and between two forms of final statement of if ... else ... series of statements assuming every possible condition is accounted for as shown in simple specimen / example / sample below (not snippet as it is not a snip of a larger code base). 1st style : if(expression == true) {...} else {...} 2nd style : if(expression == true) {...} else if(expression == false) {...} Note it is the final statement I am inquiring regards. Do your kind selves accept the default final result as shown in 1st style or perform explicit unnecessary test as shown in 2nd style for no other reason than to make the code self documenting and easier to understand in particular for a complex lengthy series of conditions. btw in 2nd style on occasion I add as final statement else throw who_the_heck_knows_what_happened; Thank You Kindly [edit] I have concluded kind Jacquers is quite correct. As it happened upon some coding just now of a simple series of such it was evident an explicit final test results in confusion as it is clearly not necessary. However in a lengthy complex series an explicit test makes code self documenting and so simpler to understand. KISS

                                RaviBeeR Offline
                                RaviBeeR Offline
                                RaviBee
                                wrote on last edited by
                                #48

                                I prefer the K&R format and always use braces to promote code safety.

                                if (condition) {
                                ...;
                                }
                                else {
                                ...;
                                }

                                /ravi

                                My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                                T B 2 Replies Last reply
                                0
                                • T trønderen

                                  I do hope that the "==true" and "==false" are not meant literally! A programmer comparing a logical expression against "true" or "false" have not understood what is meant by a logical expression. I wonder how many of those programming that way also speak that way! "If you have a moment to spare is true, I want a talk with you", or "If the door is unlocked is false, you'll find the key under the door mat" - noone that I know speaks that way. I have met a few programmers who program that way, but I never heard any of them speak with "is true" or "is false".

                                  Religious freedom is the freedom to say that two plus two make five.

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

                                  Ah, the benefits of modern languages. Waaay back in the 90s, using ANSI C (I was using VAX C and DEC C) the "guru" who had first designed the system, had defined TRUE as (0==0) and FALSE as (!TRUE) -- because these would be unambiguous and correct regardless of architecture (the same code had to work on QNX and DOS). Personally, I dislike how K&R and ANSI C handle true and false.

                                  1 Reply Last reply
                                  0
                                  • RaviBeeR RaviBee

                                    I prefer the K&R format and always use braces to promote code safety.

                                    if (condition) {
                                    ...;
                                    }
                                    else {
                                    ...;
                                    }

                                    /ravi

                                    My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                                    T Offline
                                    T Offline
                                    trønderen
                                    wrote on last edited by
                                    #50

                                    I make a sharp distinction between how I personally would like to format the code, and how I code when someone else will/might read it. I see so many errors caused by deep nesting and misinterpretation of indentation levels that I want a double check to detect mistakes. Therefore: 1) No indentation that is not supported by braces 2) No braces that do not adhere to the indentation level. So if I see anything like

                                    if (somecondtion)
                                    xval = 1;
                                    nextstatement;

                                    I immediately ask for permission to add the "redundant" braces. Most programmers accept this. The second point is far less accepted: As long as you are not past the closing brace, you are still in the indented block. The brace is what causes the undent. Code is read in forward direction, so the last character position before the brace is still indented. Also, the closing brace visually blurs what is the next statement. I would really want to edit the above code to

                                    if (somecondition) {
                                    xval = 1;
                                    }
                                    nextstatement;

                                    - but few other programmers agree to the indentation of the closing brace. I have to tolerate what I consider a logical inconsistency, in non-private code. I also consider as inconsistent the style suggested by some:

                                    if (somecondition)
                                    {
                                    xval = 1;
                                    }
                                    nextstatement;

                                    - you don't know that an indented block follows until after the opening brace. Inserting indenting space before it cannot be logically justified. I honestly abhor deep block nesting, in particular when it ends up in a sequence of '} } } } }'. I try to avoid that whenever possible. Get out of a given nesting level as soon as possible! So I code like

                                    FailureCode SomeMethod(int argX, float argY, sometype Z) {

                                    if (argX > maxXvalue) {
                                    return ErrorIllegalXArgument;
                                    }
                                    if (argZ == null) {
                                    return ErrorUnspecifiedZ;
                                    }

                                    statement;
                                    statement;
                                    return Success;
                                    }

                                    Today, this is accepted by most other programmers, at the method level, although the majority would like to add 'else's, including for the successful part. Sequences of 'else if' are by most not considered a new nesting level and usually accepted as a series of alternatives, although they strictly are not, by the grammar definition, of most C class languages. A similar situation can occur in the middle of a method body: Several conditions must be satisfied for some operation to be performed. The C class of languages doesn't allow you to define arbitr

                                    B 1 Reply Last reply
                                    0
                                    • T trønderen

                                      I make a sharp distinction between how I personally would like to format the code, and how I code when someone else will/might read it. I see so many errors caused by deep nesting and misinterpretation of indentation levels that I want a double check to detect mistakes. Therefore: 1) No indentation that is not supported by braces 2) No braces that do not adhere to the indentation level. So if I see anything like

                                      if (somecondtion)
                                      xval = 1;
                                      nextstatement;

                                      I immediately ask for permission to add the "redundant" braces. Most programmers accept this. The second point is far less accepted: As long as you are not past the closing brace, you are still in the indented block. The brace is what causes the undent. Code is read in forward direction, so the last character position before the brace is still indented. Also, the closing brace visually blurs what is the next statement. I would really want to edit the above code to

                                      if (somecondition) {
                                      xval = 1;
                                      }
                                      nextstatement;

                                      - but few other programmers agree to the indentation of the closing brace. I have to tolerate what I consider a logical inconsistency, in non-private code. I also consider as inconsistent the style suggested by some:

                                      if (somecondition)
                                      {
                                      xval = 1;
                                      }
                                      nextstatement;

                                      - you don't know that an indented block follows until after the opening brace. Inserting indenting space before it cannot be logically justified. I honestly abhor deep block nesting, in particular when it ends up in a sequence of '} } } } }'. I try to avoid that whenever possible. Get out of a given nesting level as soon as possible! So I code like

                                      FailureCode SomeMethod(int argX, float argY, sometype Z) {

                                      if (argX > maxXvalue) {
                                      return ErrorIllegalXArgument;
                                      }
                                      if (argZ == null) {
                                      return ErrorUnspecifiedZ;
                                      }

                                      statement;
                                      statement;
                                      return Success;
                                      }

                                      Today, this is accepted by most other programmers, at the method level, although the majority would like to add 'else's, including for the successful part. Sequences of 'else if' are by most not considered a new nesting level and usually accepted as a series of alternatives, although they strictly are not, by the grammar definition, of most C class languages. A similar situation can occur in the middle of a method body: Several conditions must be satisfied for some operation to be performed. The C class of languages doesn't allow you to define arbitr

                                      B Offline
                                      B Offline
                                      BernardIE5317
                                      wrote on last edited by
                                      #51

                                      I was recently influenced by an article recommending nesting be minimized. There are many such articles also here on this site. I also learned to detect and return from error cases as soon as possible if not immediately. re/ braces and indentation etc. it is my opinion we all process visual information in our own way. My own main rule is to write / format in a manner which is pleasing to the eye exempli gratia as two specimens (not snippets as they were obviously not taken out from a code base) below. re/ 1st specimen I prefer as below as I find your preferred style requiring greater cognitive load as there is simply more stuff to process but as stated we all process differently. Also there is the matter of screen real estate. I find it helpful for braces to align. Also the IDE provides a vertical line of dots connecting same which I find quite helpful even rely on.

                                      if (condtion) statement;
                                      next_statement;

                                      if(condition)
                                      {
                                      . statement;
                                      . statement;
                                      . statement;
                                      }

                                      I do not understand the 2nd discussion. Why not merely write

                                      if (!(argX > MaxXvalue|| argY < 0.0 || argZ == null))
                                      {
                                      statement;
                                      statement;
                                      }

                                      I agree w/ your final discussion. The purist style is a mess. In closing I have never seen do {} while (false) I now realize it is identical to if(true) {}. Do you find this style more logical or pleasing to the eye.

                                      T 1 Reply Last reply
                                      0
                                      • B BernardIE5317

                                        I was recently influenced by an article recommending nesting be minimized. There are many such articles also here on this site. I also learned to detect and return from error cases as soon as possible if not immediately. re/ braces and indentation etc. it is my opinion we all process visual information in our own way. My own main rule is to write / format in a manner which is pleasing to the eye exempli gratia as two specimens (not snippets as they were obviously not taken out from a code base) below. re/ 1st specimen I prefer as below as I find your preferred style requiring greater cognitive load as there is simply more stuff to process but as stated we all process differently. Also there is the matter of screen real estate. I find it helpful for braces to align. Also the IDE provides a vertical line of dots connecting same which I find quite helpful even rely on.

                                        if (condtion) statement;
                                        next_statement;

                                        if(condition)
                                        {
                                        . statement;
                                        . statement;
                                        . statement;
                                        }

                                        I do not understand the 2nd discussion. Why not merely write

                                        if (!(argX > MaxXvalue|| argY < 0.0 || argZ == null))
                                        {
                                        statement;
                                        statement;
                                        }

                                        I agree w/ your final discussion. The purist style is a mess. In closing I have never seen do {} while (false) I now realize it is identical to if(true) {}. Do you find this style more logical or pleasing to the eye.

                                        T Offline
                                        T Offline
                                        trønderen
                                        wrote on last edited by
                                        #52

                                        BernardIE5317 wrote:

                                        I find it helpful for braces to align.

                                        It provides a 'graphic consistency', but it breaks with the logic of braces and indents representing the same structural property. For the closing brace, you are not yet out of the block, yet you undent it. Also, the first line, with the 'if' terminates abruptly without explanation. Putting the brace at the end of the line explains what is happening: You will now see an indented block that is the 'if' clause. As I illustrated, I accept a single short statement after the if-condition; then you will see a line terminated with a semicolon, and you know that the if-clause is complete, and no indented if-clause follows. Another reason why I do not want the opening brace on a new line: It visually clutters the 'if'. With the 'if' having blank space underneath it, it stands out as the kind of statement owning the block; you can see from a far distance that is isn't a e.g. while or for loop. Similar for the closing brace: It clutters up what will happen after the conditional block.

                                        I do not understand the 2nd discussion.

                                        Consider it a somewhat stylized, simplified example. First, each of the tests may be far more complex than a simple comparison, and the total combined expression may be lengthy, maybe not fitting on a line. More important: If the tests are conceptually independent, testing three separate aspects, that should be reflected by writing them as three separate tests. They are three different reasons for not performing the operation (or for returning from the method), not a single complex reason. A test such as 'if (ch1 >= 'a' && ch1 <= 'z')' is one conceptually homogenous test that belongs in one single if-condition. Three different tests on three distinct variables is rarely similarly homogenous. Third: In many cases, a test that leads to the operation not being performed may lead to e.g. a status value being set. Each test may lead to a different status value. If you mold together the three tests, you cannot fit such handling into your layout rules. Also, note that in my final example, which is my preferred one, the three conditions are clearly separated from the operation code, so that you see what is the condition, what is the operation. (I should have inserted a blank line after the conditions in the example with the 'break;' at separate lines - I always do in my code, and leaving it out here is at the level of a typo :-).)

                                        B 1 Reply Last reply
                                        0
                                        • RaviBeeR RaviBee

                                          I prefer the K&R format and always use braces to promote code safety.

                                          if (condition) {
                                          ...;
                                          }
                                          else {
                                          ...;
                                          }

                                          /ravi

                                          My new year resolution: 2048 x 1536 Home | Articles | My .NET bits | Freeware ravib(at)ravib(dot)com

                                          B Offline
                                          B Offline
                                          BernardIE5317
                                          wrote on last edited by
                                          #53

                                          May I please inquire the manner in which code safety is promoted via the presented K&R format. I assume it refers to the risk of programmer error making the assumption braces reduce the risk of further editing incorrectly. That seems reasonable. Than there are the matters of personal preference re/ visual processing also screen real estate. Perhaps in future the IDE will provide a feature I have contemplated id est coloring each block in a differing color. btw the matching braces which are not vertically aligned in your presented specimen prevent the IDE from displaying vertical dots betwixt them. A feature I quite prefer. -kind regards

                                          RaviBeeR 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