Presentation is loading. Please wait.

Presentation is loading. Please wait.

Software Construction 1 (0721385) First Semester 2014-2015 Dr. Samer Odeh Hanna (PhD) Office: IT 327.

Similar presentations


Presentation on theme: "Software Construction 1 (0721385) First Semester 2014-2015 Dr. Samer Odeh Hanna (PhD) Office: IT 327."— Presentation transcript:

1 Software Construction 1 (0721385) First Semester 2014-2015 Dr. Samer Odeh Hanna (PhD) http://philadelphia.edu.jo/academics/shanna Office: IT 327

2 Software Construction 2 Chapter 3: Defensive Programming

3 Software Construction 3 Introduction  The idea of defensive programming is based on defensive driving  In defensive programming, the main idea is that if a routine is passed bad data, it won't be hurt, even if the bad data is another routine's fault.

4 Software Construction 4 3.1 Protecting Your Program from Invalid Inputs A good program never put out garbage, regardless of what it takes in. A good program uses:  "Garbage in, nothing out"  "Garbage in, error message out"  "No garbage allowed in"

5 Software Construction 5 There are three general ways to handle garbage in:  Check the values of all data from external sources  Attempt buffer overflows  Inject SQL commands  Inject HTML or XML code and so on  Check the values for all routine input parameters  Decide how to handle bad inputs

6 Software Construction 6 3.2 Assertions  An assertion is code that is used during development that allows a program to check itself as it runs. When an assertion is true, that means everything is operating as expected, when it is false, that means it has detected an unexpected error in the code. assert denominator != 0 : "denominator is unexpectedly equal to 0.";

7 Software Construction 7 Guidelines for Using Assertions  Use error-handling code for conditions you expect to occur; use assertions for conditions that should never occur  Avoid putting executable code into assertions Visual Basis example of a dangerous use of an assertion Debug.Assert (PerformAction( ) ) ' Could no perform action Visual Basis example of a safe use of an assertion actionPerformed = PerformAction( ) Debug.Assert (actionPerformed )

8 Software Construction 8 Cont.  Use assertions to document and verify preconditions and Postconditions Visual Basic example of using assertions to document preconditions and Postconditions Private Function Velocity ( ByVal latitude As Single, ByVal longtitude As Single, ByVal elevation As Single ) As Single ' Preconditions Debug.Assert ( -90 <= latitude And latitude <=90) Debug.Assert ( 0 <= longitude And longitude <360) Debug.Assert ( -500 <= elevation And elevation <= 75000) ' PostConditions Debug.Assert ( 0 <= returnVelocity and returnVelocity <=600 ) ' return value Velocity = returnVelocity End Function

9 Software Construction 9  For highly robust code, assert and then handle the error anyway Visual Basic example of using assertions to document preconditions and Postconditions Private Function Velocity ( ByVal latitude As Single, ByVal longitude As Single, ByVal elevation As Single ) As Single Assertion code ' Preconditions Debug.Assert ( -90 <= latitude And latitude <=90) Debug.Assert ( 0 <= longitude And longitude <360) Debug.Assert ( -500 <= elevation And elevation <= 75000) ….. ' Sanitize input data. Values should be within the ranges asserted above ' but if a value is not within its valid range, it will be changed to the ' closet legal value If ( latitude < -90 ) Then Code that handles bad input data at run-time latitude = -90 ElseIf ( latitude > 90 ) Then latitude = 90 End If IF ( longitude < 0 ) Then Longitude = 0 ElseIF ( longitude > 360 ) Then … End Function

10 Software Construction 10 3.3 Error-Handling Techniques 1. Return a neutral value 2. Substitute the next piece of valid data 3. Return the same answer as previous time 4. Substitute the closet legal value 5. Log a warning message to a file 6. Return an error code 7. Call an error-processing routine/object 8. Display an error message wherever the error is encountered 9. Handle the error in whatever way works best locally 10. Shut down

11 Software Construction 11 Differences between assertion and error handling techniques AssertionError Handling Technique An assertion is code that is used during development Error handling techniques is code that is used during development and after delivery assertions for conditions that should never occur error-handling code is used for conditions you expect to occur the corrective action is to change the program's source code, recompile, and release a new version of a software. the corrective action is merely to handle an error gracefully

12 Software Construction 12 Robustness vs. Correctness  Correctness means never returning an inaccurate result; returning no result is better than returning an inaccurate result.  Robustness means always trying to do something that will allow the software to keep operating, even if that leads to results that are inaccurate sometimes.  Some applications tend to favor correctness to robustness and others favor robustness to correctness.

13 Software Construction 13 3.3 Exceptions  Exceptions are a specific means by which code can pass along errors or exceptional events to the code that called it. If code in one routine encounters an unexpected condition that it does not know how to handle, it throws an exception, essentially throwing up its hands and yelling, "I do not know what to do about this – I sure hope somebody else knows how to handle it!"  Visit http://www.dotnetperls.com/exception for exampleshttp://www.dotnetperls.com/exception

14 Software Construction 14 Example using System; class Program { static void Main() { try { int value = 1 / int.Parse("0"); Console.WriteLine(value); } catch (Exception ex) { Console.WriteLine(ex.Message); }

15 Software Construction 15 Custom Exception Example using System; class TestException : Exception { public override string Message { get { return "This exception means something bad happened"; } } class Program { static void Main() { try { throw new TestException(); } catch (TestException ex) { Console.WriteLine(ex.Message); }

16 Software Construction 16 Exceptions (Cont.) Suggestions for realizing the benefits of exceptions and avoiding the difficulties often associated with them.  Use exceptions to notify other parts of the program about errors that should not be ignored  If an error condition can be handled locally, handle it locally  Avoid throwing exceptions in constructors and destructors  Throw exceptions at the right level of abstraction  Include in the exception message all information that led to the exception

17 Software Construction 17 Cont.  Avoid empty catch blocks  Standardize your project's use of exceptions  Consider alternatives to exceptions

18 Software Construction 18 3.4 Barricade  Barricade your Program to Contain the Damage Caused by Errors  Barricades are a damage-containment strategy  One way to barricade for defensive programming purpose is to design certain interfaces as boundaries to "safe" areas

19 Software Construction 19 Relationship between Barricades and Assertions  Routines that are outside the barricade should use error handling  Routines inside the barricade should use assertions

20 Software Construction 20 Questions?


Download ppt "Software Construction 1 (0721385) First Semester 2014-2015 Dr. Samer Odeh Hanna (PhD) Office: IT 327."

Similar presentations


Ads by Google