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. What is meant by Defensive Programming?

What is meant by Defensive Programming?

Scheduled Pinned Locked Moved The Lounge
questioncollaboration
25 Posts 22 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.
  • A Amarnath S

    No matter how my team-members code, my code should work fine :confused:

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

    It's like defensive driving. Run all red lights, stop signs, never yield, in other words, put everyone on the defensive. Marc

    Imperative to Functional Programming Succinctly Contributors Wanted for Higher Order Programming Project!

    1 Reply Last reply
    0
    • M Maximilien

      "Defensive programming is a form of defensive design intended to ensure the continuing function of a piece of software under unforeseen circumstances. The idea can be viewed as reducing or eliminating the prospect of Finagle's law having effect" [^] IMO, this goes with design by contract[^] programming. (pre and post conditions) In short, you make your own code fool proof according to the design and architecture (and contract) of the existing code. BAD EXAMPLE BELOW ... DO NOT USED... I keep it there just because I suck this morning. As a (very simplified example) (in c-ish language) If the design (contract) say that p can be invalid, then you need to handle that case.

      void f ( SomeClass* p )
      {
      p->doSomething();
      }

      will crash is p is invalid. defensive programming will have something like:

      void f ( SomeClass* p )
      {
      if (p)
      p->doSomething();
      }

      or

      void f ( SomeClass* p )
      {
      if ( invalid(p))
      {
      assert_and_log_message("invalid p in function f");
      return;
      }
      p->doSomething();
      }

      In both case, your own code will not crash.

      I'd rather be phishing!

      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #10

      Looks like a great way to introduce bugs. Now the caller has absolutely no idea that the argument was invalid, and that the method didn't actually do what they were expecting it to do, and will continue to execute despite the system being in an invalid state. Throwing an exception when given invalid input would be the ideal, but even crashing would be better than just doing nothing! :doh:


      "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

      M 1 Reply Last reply
      0
      • A Amarnath S

        No matter how my team-members code, my code should work fine :confused:

        OriginalGriffO Offline
        OriginalGriffO Offline
        OriginalGriff
        wrote on last edited by
        #11

        Fitting the computer with Armer Response and hooking it up to the default "bleep" in your application.

        Bad command or file name. Bad, bad command! Sit! Stay! Staaaay...

        "I have no idea what I did, but I'm taking full credit for it." - ThisOldTony
        "Common sense is so rare these days, it should be classified as a super power" - Random T-shirt

        1 Reply Last reply
        0
        • A Amarnath S

          No matter how my team-members code, my code should work fine :confused:

          M Offline
          M Offline
          Munchies_Matt
          wrote on last edited by
          #12

          Passing the blame in meetings.

          1 Reply Last reply
          0
          • Richard DeemingR Richard Deeming

            Looks like a great way to introduce bugs. Now the caller has absolutely no idea that the argument was invalid, and that the method didn't actually do what they were expecting it to do, and will continue to execute despite the system being in an invalid state. Throwing an exception when given invalid input would be the ideal, but even crashing would be better than just doing nothing! :doh:


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

            M Offline
            M Offline
            Maximilien
            wrote on last edited by
            #13

            Well you are right My example was poorly designed.

            I'd rather be phishing!

            K 1 Reply Last reply
            0
            • A Amarnath S

              No matter how my team-members code, my code should work fine :confused:

              E Offline
              E Offline
              Eytukan
              wrote on last edited by
              #14

              Here[^]

              Starting to think people post kid pics in their profiles because that was the last time they were cute - Jeremy.

              1 Reply Last reply
              0
              • A Amarnath S

                No matter how my team-members code, my code should work fine :confused:

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

                It means get dirt on program manager, or boss of program manager, so you will not be fired because they are afraid of you.

                «I want to stay as close to the edge as I can without going over. Out on the edge you see all kinds of things you can't see from the center» Kurt Vonnegut.

                1 Reply Last reply
                0
                • A Amarnath S

                  No matter how my team-members code, my code should work fine :confused:

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

                  It works on my computer... ;P

                  Z 1 Reply Last reply
                  0
                  • A Amarnath S

                    No matter how my team-members code, my code should work fine :confused:

                    M Offline
                    M Offline
                    Mycroft Holmes
                    wrote on last edited by
                    #17

                    First you need to remember your user are absolute bloody idiots who have no regard for logic and no common sense, now you need to deal with it, validate and check everything. A REALLY defensive program does not need any internal error trapping. Better still just disconnect the keyboard and mouse, then they can't screw your app.

                    Never underestimate the power of human stupidity RAH

                    1 Reply Last reply
                    0
                    • P PIEBALDconsult

                      It works on my computer... ;P

                      Z Offline
                      Z Offline
                      zandam
                      wrote on last edited by
                      #18

                      "I tested the code on my computer and everything worked smooth, I have no idea why it crashes so brutally on a different machine... perhaps that computer is the problem..." - me, while fixing a stupid typo.

                      1 Reply Last reply
                      0
                      • A Amarnath S

                        No matter how my team-members code, my code should work fine :confused:

                        R Offline
                        R Offline
                        R Erasmus
                        wrote on last edited by
                        #19

                        Assume you will have a software tester that will try to break the function you wrote (that is their job) in anyway they can think of without editing the actual function (thus by only modifying the inputs (input arguments/global variables)), and try to prevent them from doing so.

                        "Program testing can be used to show the presence of bugs, but never to show their absence." << please vote!! >>

                        1 Reply Last reply
                        0
                        • A Amarnath S

                          No matter how my team-members code, my code should work fine :confused:

                          K Offline
                          K Offline
                          Kirk 10389821
                          wrote on last edited by
                          #20

                          I always thought about programming differently after I accidentally coded a few infinite loops that crashed because of lack of stack space, or what not... Later, it was described as defensive programming. My favorite example, is one I blew up. Given a string, pad it to the left until it is 32 characters in length. A$ = " " + A$ until len(A$) = 32 Which, of course, if you are given a string that is already too long, this will crash. So, quickly I learned While len(A$) < 32 do A$ = " " + A$ Always look for the comparison that avoids doing work under the most conditions. Here, there are a LOT of times you know to stop. The = was limited to exactly one condition. That one lesson, I have used over the years, and I refactor code that is logically correct when changed to be like this. The reduction of errors/issues is amazing. (truth is, I hate debugging, and prefer to desk check my code. I grew up with OVERNIGHT compilers, so syntax errors cost you a day. In fact, all errors cost you a day)

                          L 1 Reply Last reply
                          0
                          • S Super Lloyd

                            I think it's probably very simple which probably already do... it's when you write some public method you don't just assume that the parameter will be kind of alright, but you cater for inappropriate input, such as null, large integer (causing overflow) etc, etc...

                            All in one Menu-Ribbon Bar DirectX for WinRT/C# since 2013! Taking over the world since 1371!

                            W Offline
                            W Offline
                            Wynter Dragon
                            wrote on last edited by
                            #21

                            Always validate your parameters and assume your user is an absolute moron. Then set up logging and early reporting messages back to you so that when they call you up all frantic you already have the problem solved. ;) It's how Scotty does it... "Aye Cap'n"

                            1 Reply Last reply
                            0
                            • K Kirk 10389821

                              I always thought about programming differently after I accidentally coded a few infinite loops that crashed because of lack of stack space, or what not... Later, it was described as defensive programming. My favorite example, is one I blew up. Given a string, pad it to the left until it is 32 characters in length. A$ = " " + A$ until len(A$) = 32 Which, of course, if you are given a string that is already too long, this will crash. So, quickly I learned While len(A$) < 32 do A$ = " " + A$ Always look for the comparison that avoids doing work under the most conditions. Here, there are a LOT of times you know to stop. The = was limited to exactly one condition. That one lesson, I have used over the years, and I refactor code that is logically correct when changed to be like this. The reduction of errors/issues is amazing. (truth is, I hate debugging, and prefer to desk check my code. I grew up with OVERNIGHT compilers, so syntax errors cost you a day. In fact, all errors cost you a day)

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

                              Kirk 10389821 wrote:

                              While len(A$) < 32 do A$ = " " + A$

                              Why use a loop when you can do something like A$ = Right(put 32 spaces in quotes here + A$, 32) Curious - if I actually put 32 spaces in quotes, it gets trimmed. hmmm.

                              There are strangers on the Plain, Croaker

                              K 1 Reply Last reply
                              0
                              • L Lost User

                                Kirk 10389821 wrote:

                                While len(A$) < 32 do A$ = " " + A$

                                Why use a loop when you can do something like A$ = Right(put 32 spaces in quotes here + A$, 32) Curious - if I actually put 32 spaces in quotes, it gets trimmed. hmmm.

                                There are strangers on the Plain, Croaker

                                K Offline
                                K Offline
                                Kirk 10389821
                                wrote on last edited by
                                #23

                                Oh, I have done it that way in a hurry! But what happens when len(A$) is NEAR the limit of a string length (ie has less than 32 characters left). You could actually lose the right side of the string!!! Also, the 32 was chosen for simplicity, as was the space. I believe the actual code had a variable for the length, and another for the padding character. But the nuances is what makes defensive programming powerful. Most people don't think in terms of limits. They EXPECT a "small" string to be passed in when they are WRITING the code, and it NEVER dawns on them how the code could be called in the future. I know from first (and second) hand experience that defensive style programming reduces errors and the debugging efforts required. I would rather fail with ASSERT() failures than to let code execute with bad parameters and pray for good luck.

                                1 Reply Last reply
                                0
                                • M Maximilien

                                  Well you are right My example was poorly designed.

                                  I'd rather be phishing!

                                  K Offline
                                  K Offline
                                  kdmote
                                  wrote on last edited by
                                  #24

                                  Hey, props to you for just striking out your code instead of deleting it. I think it is fantastic when people are humble (and self-confident) enough to let others learn from their mistakes. (Especially because I'm sure I might have made the same one!)

                                  1 Reply Last reply
                                  0
                                  • A Amarnath S

                                    No matter how my team-members code, my code should work fine :confused:

                                    S Offline
                                    S Offline
                                    Sucramsy
                                    wrote on last edited by
                                    #25

                                    I knew a VBA programmer who used "On Error Resume Next" X| as the first line of every Procedure/Function/Method. System never crashed. Half the code never ran but it never crashed.

                                    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