211 likes | 264 Views
Software Construction. (0721385) First Semester 2017-2018 Dr. Samer Odeh Hanna http://philadelphia.edu.jo/academics/shanna Office: IT 313. Chapter 3: Defensive Programming. Introduction. The idea of defensive programming is based on defensive driving
E N D
Software Construction (0721385) First Semester 2017-2018 Dr. Samer Odeh Hanna http://philadelphia.edu.jo/academics/shanna Office: IT 313
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.
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"
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
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.";
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 )
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
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
3.3 Error-Handling Techniques • Return a neutral value • Substitute the next piece of valid data • Return the same answer as previous time • Substitute the closet legal value • Log a warning message to a file • Return an error code • Call an error-processing routine/object • Display an error message wherever the error is encountered • Handle the error in whatever way works best locally • Shut down
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.
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 examples
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); } } }
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); } } }
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
Cont. • Avoid empty catch blocks • Standardize your project's use of exceptions • Consider alternatives to exceptions
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
Relationship between Barricades and Assertions • Routines that are outside the barricade should use error handling • Routines inside the barricade should use assertions