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
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. Other Discussions
  3. The Insider News
  4. Reduce code complexity: Guard clauses

Reduce code complexity: Guard clauses

Scheduled Pinned Locked Moved The Insider News
visual-studiocomalgorithms
17 Posts 11 Posters 0 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.
  • K Kent Sharkey

    Rock and Null[^]:

    Almost every software engineer fights a never-ending fight: we strive to make our codebase simpler and thus more readable every day.

    If you don't guard your clauses, who knows what may happen to them

    Yeah, very lame. It's Sunday, and my brain isn't working right now.

    D Offline
    D Offline
    David ONeil
    wrote on last edited by
    #2

    Guard clauses cause clustering complexity collapse. Claus that's the way they roll! :rimshot: - followed by deathly silence.

    The Science of King David's Court | Object Oriented Programming with C++

    1 Reply Last reply
    0
    • K Kent Sharkey

      Rock and Null[^]:

      Almost every software engineer fights a never-ending fight: we strive to make our codebase simpler and thus more readable every day.

      If you don't guard your clauses, who knows what may happen to them

      Yeah, very lame. It's Sunday, and my brain isn't working right now.

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

      It's brief and recommends putting guards in their own if statements. It will trigger those who cleave to the shibboleth that a function should only have one return statement.

      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>

      realJSOPR D 2 Replies Last reply
      0
      • Greg UtasG Greg Utas

        It's brief and recommends putting guards in their own if statements. It will trigger those who cleave to the shibboleth that a function should only have one return statement.

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

        realJSOPR Offline
        realJSOPR Offline
        realJSOP
        wrote on last edited by
        #4

        I cleave to that shibboleth.

        ".45 ACP - because shooting twice is just silly" - JSOP, 2010
        -----
        You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
        -----
        When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

        G 1 Reply Last reply
        0
        • Greg UtasG Greg Utas

          It's brief and recommends putting guards in their own if statements. It will trigger those who cleave to the shibboleth that a function should only have one return statement.

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

          D Offline
          D Offline
          den2k88
          wrote on last edited by
          #5

          Like PC-Lint and MISRA standards.

          GCS d--(d-) s-/++ a C++++ U+++ P- L+@ E-- W++ N+ o+ K- w+++ O? M-- V? PS+ PE- Y+ PGP t+ 5? X R+++ tv-- b+(+++) DI+++ D++ G e++ h--- r+++ y+++*      Weapons extension: ma- k++ F+2 X

          1 Reply Last reply
          0
          • K Kent Sharkey

            Rock and Null[^]:

            Almost every software engineer fights a never-ending fight: we strive to make our codebase simpler and thus more readable every day.

            If you don't guard your clauses, who knows what may happen to them

            Yeah, very lame. It's Sunday, and my brain isn't working right now.

            Richard DeemingR Online
            Richard DeemingR Online
            Richard Deeming
            wrote on last edited by
            #6

            Quis custodes custodit? :-D


            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

            "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

            1 Reply Last reply
            0
            • K Kent Sharkey

              Rock and Null[^]:

              Almost every software engineer fights a never-ending fight: we strive to make our codebase simpler and thus more readable every day.

              If you don't guard your clauses, who knows what may happen to them

              Yeah, very lame. It's Sunday, and my brain isn't working right now.

              G Offline
              G Offline
              Gary Wheeler
              wrote on last edited by
              #7

              A completely stupid idea. It adds a thrown exception that functions solely as a goto.

              Software Zen: delete this;

              K Greg UtasG 2 Replies Last reply
              0
              • realJSOPR realJSOP

                I cleave to that shibboleth.

                ".45 ACP - because shooting twice is just silly" - JSOP, 2010
                -----
                You can never have too much ammo - unless you're swimming, or on fire. - JSOP, 2010
                -----
                When you pry the gun from my cold dead hands, be careful - the barrel will be very hot. - JSOP, 2013

                G Offline
                G Offline
                Gary Wheeler
                wrote on last edited by
                #8

                Agreed.

                Software Zen: delete this;

                1 Reply Last reply
                0
                • K Kent Sharkey

                  Rock and Null[^]:

                  Almost every software engineer fights a never-ending fight: we strive to make our codebase simpler and thus more readable every day.

                  If you don't guard your clauses, who knows what may happen to them

                  Yeah, very lame. It's Sunday, and my brain isn't working right now.

                  M Offline
                  M Offline
                  Marc Clifton
                  wrote on last edited by
                  #9

                  It's so sad that other programmers that I may end up working with at some point read that drivel and adopt it.

                  Latest Articles:
                  DivWindow: Size, drag, minimize, and maximize floating windows with layout persistence

                  D B 2 Replies Last reply
                  0
                  • G Gary Wheeler

                    A completely stupid idea. It adds a thrown exception that functions solely as a goto.

                    Software Zen: delete this;

                    K Offline
                    K Offline
                    Kent Sharkey
                    wrote on last edited by
                    #10

                    At least with a GOTO you can get back to where you were - much more difficult with exceptions. :sigh:

                    TTFN - Kent

                    G 1 Reply Last reply
                    0
                    • K Kent Sharkey

                      At least with a GOTO you can get back to where you were - much more difficult with exceptions. :sigh:

                      TTFN - Kent

                      G Offline
                      G Offline
                      Gary Wheeler
                      wrote on last edited by
                      #11

                      True, but then I'm a purist. I haven't used a goto statement in over 20 years. I will admit I use break and continue, but they are 'structured' to my way of thinking.

                      Software Zen: delete this;

                      1 Reply Last reply
                      0
                      • G Gary Wheeler

                        A completely stupid idea. It adds a thrown exception that functions solely as a goto.

                        Software Zen: delete this;

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

                        Did I miss something? An exception is more than a goto, because it can jump outside of the current scope. This is very useful for aborting work that has run into a serious error, when it is appropriate to exit a chain of function calls and recover from a known point well down the stack. That's actually the only thing I use exceptions for. In most cases, such as a bad argument, the function should simply return a failure result instead. EDIT: It looks like the code could well be overusing exceptions when returning a failure result would be more appropriate, so that's probably what I missed.

                        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>

                        G 1 Reply Last reply
                        0
                        • Greg UtasG Greg Utas

                          Did I miss something? An exception is more than a goto, because it can jump outside of the current scope. This is very useful for aborting work that has run into a serious error, when it is appropriate to exit a chain of function calls and recover from a known point well down the stack. That's actually the only thing I use exceptions for. In most cases, such as a bad argument, the function should simply return a failure result instead. EDIT: It looks like the code could well be overusing exceptions when returning a failure result would be more appropriate, so that's probably what I missed.

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

                          G Offline
                          G Offline
                          Gary Wheeler
                          wrote on last edited by
                          #13

                          The 'guard' code from the article was this:

                          fun guard() {
                          if (!condition1) {
                          throw Exception1()
                          }
                          doThings1()

                          if (!condition2) {
                              throw Exception2()
                          }
                          doThings2()
                          
                          if (!condition3) {
                              throw Exception3()
                          }
                          doThings3()
                          

                          }

                          This call needs to be surrounded by a try...catch in order to exactly reproduce the functionality of the original. I'm not sure which language is used for the original code; I think it may be Javascript, but the fun keyword is odd. In any case, throwing an exception in lieu of nested conditionals or a goto is overly complicated and error-inducing. Imagine debugging this sort of nonsense when the catch misses one of the exceptions thrown.

                          Software Zen: delete this;

                          1 Reply Last reply
                          0
                          • M Marc Clifton

                            It's so sad that other programmers that I may end up working with at some point read that drivel and adopt it.

                            Latest Articles:
                            DivWindow: Size, drag, minimize, and maximize floating windows with layout persistence

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

                            :omg:

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

                            1 Reply Last reply
                            0
                            • M Marc Clifton

                              It's so sad that other programmers that I may end up working with at some point read that drivel and adopt it.

                              Latest Articles:
                              DivWindow: Size, drag, minimize, and maximize floating windows with layout persistence

                              B Offline
                              B Offline
                              BillWoodruff
                              wrote on last edited by
                              #15

                              Hi Marc, Perhaps my memory is flawed, but, I seem to recall eyeballing code of yours that used preventive filters in this way. I'd appreciate your comments on my post below !

                              «The mind is not a vessel to be filled but a fire to be kindled» Plutarch

                              1 Reply Last reply
                              0
                              • K Kent Sharkey

                                Rock and Null[^]:

                                Almost every software engineer fights a never-ending fight: we strive to make our codebase simpler and thus more readable every day.

                                If you don't guard your clauses, who knows what may happen to them

                                Yeah, very lame. It's Sunday, and my brain isn't working right now.

                                B Offline
                                B Offline
                                BillWoodruff
                                wrote on last edited by
                                #16

                                I believe in anticipating/handling errors in parameter data before you get to the juicy parts, and I think guard clauses are a good example of a strategy for that. I also think liberal use of Try/Catch for things like file-ops is a good thing. Guard clauses' "virtual isolation" at the start of a method is, imho, "separation of concerns." You can easily comment them out, remove them, as conditions/state management require. However, there are other strategies. What I'd like to see is a radical extension of Attributes in C# that do AOP-like transformations, and, internally generate the equivalent of guard clauses: there's already an example of that in the semantics of the Nullable attributes: [^]. A "wedding" of unit-tests and attributes :)

                                «The mind is not a vessel to be filled but a fire to be kindled» Plutarch

                                Richard Andrew x64R 1 Reply Last reply
                                0
                                • B BillWoodruff

                                  I believe in anticipating/handling errors in parameter data before you get to the juicy parts, and I think guard clauses are a good example of a strategy for that. I also think liberal use of Try/Catch for things like file-ops is a good thing. Guard clauses' "virtual isolation" at the start of a method is, imho, "separation of concerns." You can easily comment them out, remove them, as conditions/state management require. However, there are other strategies. What I'd like to see is a radical extension of Attributes in C# that do AOP-like transformations, and, internally generate the equivalent of guard clauses: there's already an example of that in the semantics of the Nullable attributes: [^]. A "wedding" of unit-tests and attributes :)

                                  «The mind is not a vessel to be filled but a fire to be kindled» Plutarch

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

                                  BillWoodruff wrote:

                                  What I'd like to see is a radical extension of Attributes in C#

                                  You always did strike me as a radical!

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

                                  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