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

    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
                                  • 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
                                    jschell
                                    wrote on last edited by
                                    #67

                                    BernardIE5317 wrote:

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

                                    I had forgotten another variance on mandating usage.

                                    if(true == expression)

                                    Some C++ coders insisted on that because, the possibility existed that one might code the following.

                                    if(expression = true)

                                    And that is valid in C++. Myself C++ programmers not controlling the scope of the their memory allocations was always, and still is, much more of a significant problem.

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

                                      N Offline
                                      N Offline
                                      Norm Powroz
                                      wrote on last edited by
                                      #68

                                      Wholeheartedly agree! Having the braces on separate lines makes it so much easier to determine where the then/else clauses begin and end. Lining them up vertically at each indentation level also means you can easily see what goes with what, such as: if (expression) { // then result if (other condition) { // Other condition then result } else { // other condition else result } } else { // else result } I really hate code that puts all the opening braces on the if (expression) line, or the "else" line. Programmers who don't believe in clarity of their code should be banned from the practice. Don't forget -- comments can also help a lot in improving clarity.

                                      T 1 Reply Last reply
                                      0
                                      • N Norm Powroz

                                        Wholeheartedly agree! Having the braces on separate lines makes it so much easier to determine where the then/else clauses begin and end. Lining them up vertically at each indentation level also means you can easily see what goes with what, such as: if (expression) { // then result if (other condition) { // Other condition then result } else { // other condition else result } } else { // else result } I really hate code that puts all the opening braces on the if (expression) line, or the "else" line. Programmers who don't believe in clarity of their code should be banned from the practice. Don't forget -- comments can also help a lot in improving clarity.

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

                                        Norm Powroz wrote:

                                        Having the braces on separate lines makes it so much easier to determine where the then/else clauses begin and end.

                                        You have indentation for that, don't you? If you indent neither of the braces, they do not enforce the indentation, but blurs both the indentation and the keyword causing the indentation. If you indent both, the keyword is 'revealed'. And the block is extended by two two lines, making it more prominent. I think that making 'the indenting keyword' more visible (by avoiding the blurring opening brace immediately below it) is a good thing. Indenting before the opening brace is logically inconsistent - so the brace should be un-indented, at the line of the if / while / ... . Also, when you read e.g. an if, and the line ends abruptly, with no explanation, you should rather include the brace to indicate: There is an explanation - this brace tells that a block is following! The closing brace on a separate indented line ensures that the indented block is at least two lines long. That should be enough for everybody, to make sure that the block is easily identified. I think un-indented braces blur the indented block, rather than enforcing it as it should.

                                        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

                                          S Offline
                                          S Offline
                                          Stacy Dudovitz
                                          wrote on last edited by
                                          #70

                                          In reading all of the responses, I'm quite surprised that the only alternative mentioned was the tertiary operator (?: ). While it's simple to respond 'context dependent' as I saw in some of the replies, I think maybe it would help to spell out the concerns as well as offer up more choices. Let's start with the elephant in the room... readability and maintainability. They both go hand in hand to answer the question "what are you trying to do or say in the code?" In addition, some of the choices can lead to both bugs and code creep. Let's start with if/else as a potential solution to express a/the logical path to traverse. A couple of simple rules would help (these are *my* rules, some may be obvious, but some are what I call 'Where's the curly brace' religious preferences. Take everything I write here are my own style rather than engage in religiosity).

                                          if (condition 1)
                                          {
                                          // do something 1
                                          }
                                          else if (condition 2)
                                          {
                                          // do something 2
                                          }
                                          else
                                          {
                                          // do something 3
                                          }

                                          I always include the curly braces to ensure that scope is honored i.e. what code is executed based on which condition is met. Too often I've see this:

                                          if (condition 1)
                                          // do something 1
                                          else if (condition 2)
                                          // do something 2
                                          else
                                          // do something 3

                                          The problem here is if another author comes in to add/maintain the code, and adds a second line of execution to one of the conditions. If that author forgets to now add the curly braces to enclose scope, bad things happen.

                                          if (condition 1)
                                          // do something 1
                                          else if (condition 2)
                                          // do something 2A
                                          // do something 2B <-- we've exited the scope of the if/else clause. Ooops!
                                          else
                                          // do something 3

                                          In addition, the whole Nickleback induced hatred the tertiary operator hails back to a late 70's bug introduced in a version (or couple of versions) of the Whitesmiths C compiler, and has since become lore. If we are striving for readability, then:

                                          if (condition) ? "do one thing" : "do the other thing";

                                          If you are vehemently opposed to this, chances are you also avoid the null coalescing as well as other similar constructs:

                                          char *s = null;
                                          char *t = null;
                                          ...

                                          t = s ? "some string" : "some default";

                                          But really, is this the only way to proceed? How about:

                                          switch (operand)
                                          {
                                          case 1:
                                          // do something case 1
                                          break;
                                          case 2:
                                          // do something case 2
                                          break;
                                          case 3:
                                          // do something case 3

                                          J E 2 Replies 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