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.
  • 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
    Maximilien
    wrote on last edited by
    #18

    condition ? f() : g();

    :sigh:

    CI/CD = Continuous Impediment/Continuous Despair

    B T 2 Replies Last reply
    0
    • B BernardIE5317

      May I please inquire how else does one evaluate a logical expression in C++. One can write if(a) or if(!a). But these perform the same function as if(a == true) and if(a == false). if(I do not understand your meaning == true) I kindly request clarification.;

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

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

      if (doorIsLocked == true) ...

      rather than

      if (doorIsLocked) ...

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

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

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

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

      Richard Andrew x64R J 2 Replies Last reply
      0
      • M Maximilien

        condition ? f() : g();

        :sigh:

        CI/CD = Continuous Impediment/Continuous Despair

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

        Your kind suggestion ? I agree : I still agree;

        T 1 Reply Last reply
        0
        • B BernardIE5317

          Your kind suggestion ? I agree : I still agree;

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

          My suggestion: Delete every "== true" that you have ever programmed. Delete every "== false" you have ever programmed and negate the logical expression.

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

          1 Reply Last reply
          0
          • L Lost User

            Or even worse ...

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

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

            You still do not handle the null case. True story: A friend of mine, living here in Norway, is a US citizen. She was pregnant, and planned a recreation trip out of Norway, 3 months after the expected time of birth, with her baby. Even a baby needs a passport. If you live in Norway and apply for a US passport, it can (or at least could in those days, this is 35+ years ago) take half a year to get through the paper mill. The parents didn't want to know the sex of the baby before the delivery, so when they applied for a passport for the yet unborn baby, they could not state its name. They could not state its birthday. They could not provide a photo of the passport holder. Yet, the US passport authorities did issue a passport to a person of unknown sex, unknown name, unknown birthdate, with no photo or fingerprint. I am honestly surprised that none of the systems handling that passport application went into a fatal exception :-) Or maybe they did, and it had to be debugged before the passport could be issued. Maybe, 35 years ago, US passports were essentially handled through manual procedures where exceptional conditions were handled by human brains. I am not sure that all of the fully automated passport handling systems we are using today would be able to handle that passport without stumbling and falling over.

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

            J 1 Reply Last reply
            0
            • M Maximilien

              condition ? f() : g();

              :sigh:

              CI/CD = Continuous Impediment/Continuous Despair

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

              I do not understand that code - could you please rewrite it as a regex?

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

              1 Reply Last reply
              0
              • L Lost User

                Or even worse ...

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

                pkfoxP Offline
                pkfoxP Offline
                pkfox
                wrote on last edited by
                #24

                Yuck :-D

                In a closed society where everybody's guilty, the only crime is getting caught. In a world of thieves, the only final sin is stupidity. - Hunter S Thompson - RIP

                1 Reply Last reply
                0
                • L Lost User

                  Or even worse ...

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

                  CPalliniC Online
                  CPalliniC Online
                  CPallini
                  wrote on last edited by
                  #25

                  It could be worse, it could be raining:

                  //...
                  else if(marks > 80 && marks < 95)
                  {
                  //...
                  }
                  else if(marks > 70 && marks < 80)
                  {
                  //...
                  }
                  //...

                  "In testa che avete, Signor di Ceprano?" -- Rigoletto

                  In testa che avete, signor di Ceprano?

                  L 1 Reply Last reply
                  0
                  • CPalliniC CPallini

                    It could be worse, it could be raining:

                    //...
                    else if(marks > 80 && marks < 95)
                    {
                    //...
                    }
                    else if(marks > 70 && marks < 80)
                    {
                    //...
                    }
                    //...

                    "In testa che avete, Signor di Ceprano?" -- Rigoletto

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

                    Yes, I have seen that a few times in QA.

                    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

                      D Offline
                      D Offline
                      Daniel Pfeffer
                      wrote on last edited by
                      #27

                      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 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

                        Greg UtasG Offline
                        Greg UtasG Offline
                        Greg Utas
                        wrote on last edited by
                        #28

                        For a "minor matter of style", this got a lot of responses! I use style#1 if it's clear that all possibilities have been exhausted, and the ? operator if possible. But if there's a sequence of nested if statements and there's any possibility that not all combinations have been accounted for, I use style#2 with the throw statement after the else. Defensive coding takes very little time compared to that which is otherwise wasted hunting down mysterious bugs.

                        Robust Services Core | Software Techniques for Lemmings | Articles
                        The fox knows many things, but the hedgehog knows one big thing.

                        <p><a href="https://github.com/GregUtas/robust-services-core/blob/master/README.md">Robust Services Core</a>
                        <em>The fox knows many things, but the hedgehog knows one big thing.</em></p>

                        0 1 Reply Last reply
                        0
                        • Greg UtasG Greg Utas

                          For a "minor matter of style", this got a lot of responses! I use style#1 if it's clear that all possibilities have been exhausted, and the ? operator if possible. But if there's a sequence of nested if statements and there's any possibility that not all combinations have been accounted for, I use style#2 with the throw statement after the else. Defensive coding takes very little time compared to that which is otherwise wasted hunting down mysterious bugs.

                          Robust Services Core | Software Techniques for Lemmings | Articles
                          The fox knows many things, but the hedgehog knows one big thing.

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

                          But you don't really mean something like?

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

                          Greg UtasG honey the codewitchH 2 Replies Last reply
                          0
                          • T trønderen

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

                            if (doorIsLocked == true) ...

                            rather than

                            if (doorIsLocked) ...

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

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

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

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

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

                            trønderen wrote:

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

                            Incorrect. Two plus two making five is provably incorrect. Religious freedom is the freedom to believe things that cannot be proven.

                            The difficult we do right away... ...the impossible takes slightly longer.

                            T 1 Reply Last reply
                            0
                            • Richard Andrew x64R Richard Andrew x64

                              trønderen wrote:

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

                              Incorrect. Two plus two making five is provably incorrect. Religious freedom is the freedom to believe things that cannot be proven.

                              The difficult we do right away... ...the impossible takes slightly longer.

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

                              Religious freedom is the freedom to be irrational. If you reject all irrationality, then you reject religion. We cannot forbid irrationality and still claim that we have full religious freedom. Using "two plus two make five" as an example is a way to make the irrationality (very) explicit.

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

                              1 Reply Last reply
                              0
                              • 0 0x01AA

                                But you don't really mean something like?

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

                                Greg UtasG Offline
                                Greg UtasG Offline
                                Greg Utas
                                wrote on last edited by
                                #32

                                No throw here. It's clear that something above will get executed, and the (!expression) is also redundant.

                                Robust Services Core | Software Techniques for Lemmings | Articles
                                The fox knows many things, but the hedgehog knows one big thing.

                                <p><a href="https://github.com/GregUtas/robust-services-core/blob/master/README.md">Robust Services Core</a>
                                <em>The fox knows many things, but the hedgehog knows one big thing.</em></p>

                                1 Reply Last reply
                                0
                                • T trønderen

                                  You still do not handle the null case. True story: A friend of mine, living here in Norway, is a US citizen. She was pregnant, and planned a recreation trip out of Norway, 3 months after the expected time of birth, with her baby. Even a baby needs a passport. If you live in Norway and apply for a US passport, it can (or at least could in those days, this is 35+ years ago) take half a year to get through the paper mill. The parents didn't want to know the sex of the baby before the delivery, so when they applied for a passport for the yet unborn baby, they could not state its name. They could not state its birthday. They could not provide a photo of the passport holder. Yet, the US passport authorities did issue a passport to a person of unknown sex, unknown name, unknown birthdate, with no photo or fingerprint. I am honestly surprised that none of the systems handling that passport application went into a fatal exception :-) Or maybe they did, and it had to be debugged before the passport could be issued. Maybe, 35 years ago, US passports were essentially handled through manual procedures where exceptional conditions were handled by human brains. I am not sure that all of the fully automated passport handling systems we are using today would be able to handle that passport without stumbling and falling over.

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

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

                                  trønderen wrote:

                                  this is 35+ years ago ... surprised that none of the systems handling that passport application went into a fatal exception

                                  That long ago might not have been a system. Might have been a person. Could also just be a special case that they handle.

                                  1 Reply Last reply
                                  0
                                  • T trønderen

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

                                    if (doorIsLocked == true) ...

                                    rather than

                                    if (doorIsLocked) ...

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

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

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

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

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

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

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

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

                                    if (p == true) ...

                                    1 Reply Last reply
                                    0
                                    • Sander RosselS Sander Rossel

                                      if (expression)
                                      {

                                      }
                                      else
                                      {

                                      }

                                      Everything else is just unnecessary typing/reading.

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

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

                                      I like things more compact

                                      if ( expression ) {

                                      } else {

                                      }

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

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

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

                                      C 1 Reply Last reply
                                      0
                                      • B BernardIE5317

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

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

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

                                        #include

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

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

                                        return 0;
                                        }

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

                                        #define true 3

                                        Mircea

                                        1 Reply Last reply
                                        0
                                        • B BernardIE5317

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

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

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

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

                                          0 T 2 Replies Last reply
                                          0
                                          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