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

    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
                • T trønderen

                  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 Offline
                  B Offline
                  BernardIE5317
                  wrote on last edited by
                  #54

                  Thank you for your kind explanation re/ the 2nd discussion. It makes sense. re/ graphical consistency It seems to me text and its arrangement is a kind of graphics. I find it helpful to view code in just such a graphical manner than to study / examine further as needed. Also I kindly request your opinion of the IDE feature id est vertical dots connecting vertically aligned matching braces. - kind regards

                  T 1 Reply Last reply
                  0
                  • B BernardIE5317

                    Thank you for your kind explanation re/ the 2nd discussion. It makes sense. re/ graphical consistency It seems to me text and its arrangement is a kind of graphics. I find it helpful to view code in just such a graphical manner than to study / examine further as needed. Also I kindly request your opinion of the IDE feature id est vertical dots connecting vertically aligned matching braces. - kind regards

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

                    BernardIE5317 wrote:

                    I kindly request your opinion of the IDE feature id est vertical dots connecting vertically aligned matching braces.

                    Visual Studio provides such vertical dots regardless of brace alignment. It doesn't go by the braces, but by the statement structure. There is, however, no indication of inconsistent indentation: If you undent a few lines in the middle of a block, there is no warning. You might notice that the last line before the undent is not a single closing brace (as it should be) but VS won't tell you explicitly. I am generally positive to the dot columns, but personally, I see moderate need for them. One reason is that I tend to keep the number of indentation levels so low that I can follow it by the indentations alone. Second: The dot columns really says nothing that the indentation doesn't. For me, the indentation is far more significant. VS provides dot columns even for namespaces, classes and methods. I wish those could be separately turned off: If you really need to follow a dot column up or down, they just add to the bundle, making it more difficult to follow a specific one when you have to scroll screenfuls. I very rarely need support to know where a namespace starts and ends: With very few exceptions, all code in a source file is in the same name space. Large class definitions may have a source file to themselves, and if there are multiple classes in a single file, each of them is headed by a comment block that is hard to overlook. I need no dot column to see where a class starts/ends. If you put the text cursor (the I-beam) immediately to the left of an opening brace or to the left of a closing brace, the matching one is highlighted. If I cannot see it (e.g. because it is outside the window); I can hit ctrl-å (on my Norwegian keyboard; I don't know what is is on a US keyboard) to jump to the matching brace. Doing it with the shift key down, ctrl-Å, will highlight the entire block, everything between and including the two braces. This reduces the need for the dot columns as well. One feature that I use less frequently, but I am happy that it is available: In the window left edge, for every line opening a structure feature - name space, class, method, if-statements and loops - there is a box with a minus. Click it, and anything but the first line is collapsed. The box changes to a +. Click it (or the "..." box at the end of the line), and the hidden lines reappear. Using this feature, you can collapse, say

                    B 2 Replies Last reply
                    0
                    • T trønderen

                      BernardIE5317 wrote:

                      I kindly request your opinion of the IDE feature id est vertical dots connecting vertically aligned matching braces.

                      Visual Studio provides such vertical dots regardless of brace alignment. It doesn't go by the braces, but by the statement structure. There is, however, no indication of inconsistent indentation: If you undent a few lines in the middle of a block, there is no warning. You might notice that the last line before the undent is not a single closing brace (as it should be) but VS won't tell you explicitly. I am generally positive to the dot columns, but personally, I see moderate need for them. One reason is that I tend to keep the number of indentation levels so low that I can follow it by the indentations alone. Second: The dot columns really says nothing that the indentation doesn't. For me, the indentation is far more significant. VS provides dot columns even for namespaces, classes and methods. I wish those could be separately turned off: If you really need to follow a dot column up or down, they just add to the bundle, making it more difficult to follow a specific one when you have to scroll screenfuls. I very rarely need support to know where a namespace starts and ends: With very few exceptions, all code in a source file is in the same name space. Large class definitions may have a source file to themselves, and if there are multiple classes in a single file, each of them is headed by a comment block that is hard to overlook. I need no dot column to see where a class starts/ends. If you put the text cursor (the I-beam) immediately to the left of an opening brace or to the left of a closing brace, the matching one is highlighted. If I cannot see it (e.g. because it is outside the window); I can hit ctrl-å (on my Norwegian keyboard; I don't know what is is on a US keyboard) to jump to the matching brace. Doing it with the shift key down, ctrl-Å, will highlight the entire block, everything between and including the two braces. This reduces the need for the dot columns as well. One feature that I use less frequently, but I am happy that it is available: In the window left edge, for every line opening a structure feature - name space, class, method, if-statements and loops - there is a box with a minus. Click it, and anything but the first line is collapsed. The box changes to a +. Click it (or the "..." box at the end of the line), and the hidden lines reappear. Using this feature, you can collapse, say

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

                      Thank You Kindly . It can be instructive to learn how others use their tools. re/ undents in middle of a block I rely on the extension "Continuous Formatting". It takes care of such things for me in real time. I just now noticed the vertical dots as you stated. Good to know. - kind regards

                      1 Reply Last reply
                      0
                      • T trønderen

                        BernardIE5317 wrote:

                        I kindly request your opinion of the IDE feature id est vertical dots connecting vertically aligned matching braces.

                        Visual Studio provides such vertical dots regardless of brace alignment. It doesn't go by the braces, but by the statement structure. There is, however, no indication of inconsistent indentation: If you undent a few lines in the middle of a block, there is no warning. You might notice that the last line before the undent is not a single closing brace (as it should be) but VS won't tell you explicitly. I am generally positive to the dot columns, but personally, I see moderate need for them. One reason is that I tend to keep the number of indentation levels so low that I can follow it by the indentations alone. Second: The dot columns really says nothing that the indentation doesn't. For me, the indentation is far more significant. VS provides dot columns even for namespaces, classes and methods. I wish those could be separately turned off: If you really need to follow a dot column up or down, they just add to the bundle, making it more difficult to follow a specific one when you have to scroll screenfuls. I very rarely need support to know where a namespace starts and ends: With very few exceptions, all code in a source file is in the same name space. Large class definitions may have a source file to themselves, and if there are multiple classes in a single file, each of them is headed by a comment block that is hard to overlook. I need no dot column to see where a class starts/ends. If you put the text cursor (the I-beam) immediately to the left of an opening brace or to the left of a closing brace, the matching one is highlighted. If I cannot see it (e.g. because it is outside the window); I can hit ctrl-å (on my Norwegian keyboard; I don't know what is is on a US keyboard) to jump to the matching brace. Doing it with the shift key down, ctrl-Å, will highlight the entire block, everything between and including the two braces. This reduces the need for the dot columns as well. One feature that I use less frequently, but I am happy that it is available: In the window left edge, for every line opening a structure feature - name space, class, method, if-statements and loops - there is a box with a minus. Click it, and anything but the first line is collapsed. The box changes to a +. Click it (or the "..." box at the end of the line), and the hidden lines reappear. Using this feature, you can collapse, say

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

                        You probably will not favor the code I just now wrote but I find it easy to understand and pleasing to the eye and to the minds' eye. It is all on one line in my editor.

                        if (equal_to(minuend, subtrahend))if (!_limits) return false; else return !(*_limits)(0);

                        1 Reply Last reply
                        0
                        • T trønderen

                          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 Offline
                          C Offline
                          charlieg
                          wrote on last edited by
                          #58

                          agreed. On the other hand, I am not a religious zealot of braces. It really comes down to being able to debug - meaning putting a breakpoint on something I want to check or might need to check. Simple logic, I like (love) the ? option. Don't get me started on prefix or postfix ++ or -- operators in if statements. There is a special place in coder hell for that crap.

                          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.

                          1 Reply Last reply
                          0
                          • B BernardIE5317

                            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 Offline
                            RaviBeeR Offline
                            RaviBee
                            wrote on last edited by
                            #59

                            The K&R format is unrelated to code safety.  You get that by using braces. Using (or not using) the K&R style is purely a matter of personal taste and convention.  Code in Java and Javascript are almost always written in K&R form, but that's purely by convention. /ravi

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

                            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

                              I Offline
                              I Offline
                              Iacopo Vettori
                              wrote on last edited by
                              #60

                              I would rather use 'Assert' in the 'else {}' part to document the code and catch any possible problem, for example after a bad code editing.

                              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

                                P Offline
                                P Offline
                                Peter Kelley 2021
                                wrote on last edited by
                                #61

                                This is a good question! It happens in real life and doesn't get discussed much though! I recommend that you do *not* put in the extra test, because... > If there is any future maintenance involving a change to the condition the future programmer will need to review both conditions. Extra comprehension, extra code - more likely an error or misunderstanding. > a comment would serve the same purpose - and even can be removed safely > ? If you have both tests, then ask what's the "else" for? My experience - I've seen this done in the past, and it just trips up future programmer and confuses the human reader. [my edit: - Absolutely agree with Iacopo Vettori's comment - use 'Assert' for such cases]

                                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

                                  J Offline
                                  J Offline
                                  John Wellbelove
                                  wrote on last edited by
                                  #62

                                  Every place I've worked that used C/C++ in the past 35 years dictated this style (and it's my style of choice). if () { } else if { } else { }

                                  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

                                    M Offline
                                    M Offline
                                    MikeCO10
                                    wrote on last edited by
                                    #63

                                    As you wrote it, the 1st style is correct. Meaning an expression evaluates to true or false. The else if injects a potential question when re-reading the code that another possibility exists. If it were if(boolvar==true)..., there may be cases where the else if is appropriate.

                                    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

                                      M Offline
                                      M Offline
                                      Matt Bond
                                      wrote on last edited by
                                      #64

                                      For short, simple IF/ELSE statements, I do not use the ELSE IF (false) because it is unnecessary. If there are a large number of statements inside the IF block, then I'll use

                                      IF () {
                                      ...
                                      }
                                      else //Not {
                                      ...
                                      }

                                      This allows me to document the code with a simple comment since the IF test is too far away from the ELSE.

                                      Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere

                                      1 Reply 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.

                                        M Offline
                                        M Offline
                                        Matt Bond
                                        wrote on last edited by
                                        #65

                                        I have frequently seen programmers from India use

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

                                        in their code. I really don't understand it. But to be fair, their variables names do not make it clear that it's a Boolean value. All of my Boolean variables' names are a Yes/No question (IsValid, DoneProcessing, DoUseQuotes, etc.) so it's obviously a Boolean. When your Boolean variables are named poorly (Validation, Finish, Quotes, etc.), then you need the "== Boolean" in order to know what is going on.

                                        Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere

                                        1 Reply Last reply
                                        0
                                        • D Daniel Pfeffer

                                          As others have said, it depends on the context. I prefer a ternary operator if I must choose between returning one of two results:

                                          Foo foo = (condition ? Foo1 : Foo2);

                                          For choosing different actions, I prefer the if/then/else style, even if it would be possible to write this as a ternary expression:

                                          if (condition)
                                          {
                                          expressions1;
                                          }
                                          else
                                          {
                                          expressions2;
                                          }

                                          A "cascading" if/then/else is useful for subordinate cases:

                                          if (condition1)
                                          {
                                          expressions1;
                                          }
                                          else
                                          {
                                          if (condition2)
                                          {
                                          expressions2;
                                          }
                                          else
                                          {
                                          expressions3;
                                          }
                                          }

                                          Note that there is angoing debate whether good style requires that one wrap even single expressions in curly brackets. ( {...} }. If is usually not required by the language, but can help clarify the flow. Note that there are cases where a "cascading ternary operator" can also be useful, and actually clearer than the "cascading if/then/else".

                                          Freedom is the freedom to say that two plus two make four. If that is granted, all else follows. -- 6079 Smith W.

                                          M Offline
                                          M Offline
                                          Matt Bond
                                          wrote on last edited by
                                          #66

                                          In languages were the braces (other other syntax) is not required to block out an IF or ELSE block of code, I have seen many bugs where someone got it wrong, or edited it much later incorrectly. In my code reviews, I enforce having them for all cases because it's impossible to get wrong were the code block starts and stops; there is no interpretation of non-visible cues needed.

                                          Bond Keep all things as simple as possible, but no simpler. -said someone, somewhere

                                          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