Software Construction

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
1. Define the concept of assertions. 1 Explain the use of assertions. 2 Create Java program using assertions. 3 Run Java program using assertions. 4 2.
Detecting Bugs Using Assertions Ben Scribner. Defining the Problem  Bugs exist  Unexpected errors happen Hardware failures Loss of data Data may exist.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Software Construction 1 ( ) First Semester Dr. Samer Odeh Hanna (PhD) Office: IT 327.
Chapter 8 Designing Classes. Assignment Chapter 9 Review Exercises (Written)  R8.1 – 8.3, 8.5 – 8.7, 8. 10, 8.11, 8.13, 8.15, 8.19, 8.20 Due Friday,
Software Testing and Quality Assurance
Computer Science 340 Software Design & Testing Design By Contract.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Code Complete Steve McConnell.
PRAGMATIC PARANOIA Steven Hadfield & Anthony Rice.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
1 Defensive Programming and Debugging (Chapters 8 and 23 of Code Complete) Tori Bowman CSSE 375, Rose-Hulman September 21, 2007.
1 Debugging and Testing Overview Defensive Programming The goal is to prevent failures Debugging The goal is to find cause of failures and fix it Testing.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
Defensive Programming 1 Nikolaus Embgen. Topics 1.Motivation 2.The concept 3.What can we do? 4.How to use this? 5.What else can we do? 6.The conclusion.
Errors And How to Handle Them. GIGO There is a saying in computer science: “Garbage in, garbage out.” Is this true, or is it just an excuse for bad programming?
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Introduction to Exception Handling and Defensive Programming.
Defensive Programming, Assertions and Exceptions Designing Fault-Resistant Code SoftUni Team Technical Trainers Software University
Today’s Agenda  Reminder: HW #1 Due next class  Quick Review  Input Space Partitioning Software Testing and Maintenance 1.
Defensive Programming, Assertions and Exceptions Designing Error Steady Code SoftUni Team Technical Trainers Software University
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions and Assertions Chapter 15 – CSCI 1302.
SWE 4743 Abstract Data Types Richard Gesick. SWE Abstract Data Types Object-oriented design is based on the theory of abstract data types Domain.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
Introduction to Exceptions in Java CS201, SW Development Methods.
2.4 Exceptions n Detects try { //code that may raise an exception and/or set some condition if (condition) throw exceptionName; //Freq. A string } n Handles.
Exceptions handling Try, catch blocks Throwing exceptions.
Written by: Dr. JJ Shepherd
SE-1021 Software Engineering II
Java Exceptions a quick review….
Exception Handling in C++
CMSC202 Computer Science II for Majors Lecture 16 – Exceptions
Chapter 6 CS 3370 – C++ Functions.
Exceptions In this lecture:
CIS 200 Test 01 Review.
Logger, Assert and Invariants
Coupling and Cohesion 1.
Handling Exceptionally Sticky Problems
Defensive Programming
Object-Oriented Programming (OOP) Lecture No. 45
Testing and Debugging.
Why exception handling in C++?
Coding Defensively Coding Defensively
The Pseudocode Programming Process
Chapter 14: Exception Handling
CMSC 202 Exceptions.
Exceptions Handling the unexpected
Exceptions & Error Handling
Exception Handling Chapter 9 Edited by JJ.
Part B – Structured Exception Handling
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions 2nd Lecture.
Exceptions handling Try, catch blocks Throwing exceptions.
CISC101 Reminders Assignment 3 due next Friday. Winter 2019
CMSC 202 Exceptions 2nd Lecture.
SWE 619 Last modified Fall 2007 Saket Kaushik, Paul Ammann
Handling Exceptionally Sticky Problems
Effective Java, Chapter 9: Exceptions
Debugging and Handling Exceptions
Computer Science 340 Software Design & Testing
CMSC 202 Exceptions 2nd Lecture.
CMSC 202 Exceptions.
Software Construction
Defensive Programming
Unit Testing.
Design Contracts and Errors A Software Development Strategy
Presentation transcript:

Software Construction (0721385) Summer 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 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

Differences between assertion and error handling techniques 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

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

Avoid empty catch blocks Standardize your project's use of exceptions 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

Questions?