Coding Defensively Coding Defensively

Slides:



Advertisements
Similar presentations
Error-handling using exceptions
Advertisements

COMPUTER PROGRAMMING I Essential Standard 5.02 Understand Breakpoint, Watch Window, and Try And Catch to Find Errors.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
 Both System.out and System.err are streams—a sequence of bytes.  System.out (the standard output stream) displays output  System.err (the standard.
Exceptions and Exception Handling Carl Alphonce CSE116 March 9, 2007.
Java Programming, 3e Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
IS 1181 IS 118 Introduction to Development Tools VB Chapter 06.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
C++ fundamentals.
Microsoft Visual Basic 2005 CHAPTER 8 Using Procedures and Exception Handling.
Apply Sub Procedures/Methods and User Defined Functions
Ranga Rodrigo. Class is central to object oriented programming.
Unit Testing & Defensive Programming. F-22 Raptor Fighter.
Testing. What is Testing? Definition: exercising a program under controlled conditions and verifying the results Purpose is to detect program defects.
CIS 270—Application Development II Chapter 13—Exception Handling.
Microsoft Visual Basic 2012 Using Procedures and Exception Handling CHAPTER SEVEN.
1 Web-Enabled Decision Support Systems Objects and Procedures Don McLaughlin IE 423 Design of Decision Support Systems (304)
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.
Exceptions1 Syntax, semantics, and pragmatics. Exception create If (some error){ throw new SomeException(”some message”); } Exceptions2.
Tutorial 111 The Visual Studio.NET Environment The major differences between Visual Basic 6.0 and Visual Basic.NET are the latter’s support for true object-oriented.
Exceptions Handling Exceptionally Sticky Problems.
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Introduction to Exception Handling and Defensive Programming.
1 Chapter Nine Using GUI Objects and the Visual Studio IDE.
Web Services Error Handling and Debugging. Agenda Simple SOAP faults Advanced SOAP faults SOAP headers and faults Error handling From a Service Perspective.
Java Programming, 2E Introductory Concepts and Techniques Chapter 4 Decision Making and Repetition with Reusable Objects.
Effective Java, Chapter 9: Exceptions Items Last modified Fall 2012 Paul Ammann.
Defensive Programming. Good programming practices that protect you from your own programming mistakes, as well as those of others – Assertions – Parameter.
1 Handling Errors and Exceptions Chapter 6. 2 Objectives You will be able to: 1. Use the try, catch, and finally statements to handle exceptions. 2. Raise.
Principles of Programming & Software Engineering
Eighth Lecture Exception Handling in Java
Programming Logic and Design Seventh Edition
Data Abstraction: The Walls
Debugging and Handling Exceptions
Lecture 14 Throwing Custom Exceptions
C++ Plus Data Structures
“Form Ever Follows Function” Louis Henri Sullivan
Logger, Assert and Invariants
Handling Exceptionally Sticky Problems
Defensive Programming
Tirgul 13 Exceptions 1.
Testing and Debugging.
Computer Programming I
Using GUI Objects and the Visual Studio IDE
MFC Dialog Application
Creating and Modifying Text part 2
Functions.
Using Procedures and Exception Handling
Chapter 12 Exception Handling and Text IO
Exceptions C++ Interlude 3
Chapter 14: Exception Handling
CNS 3260 C# .NET Software Development
Partnership.
Software Construction
Exception Handling Chapter 9.
CSC 143 Error Handling Kinds of errors: invalid input vs programming bugs How to handle: Bugs: use assert to trap during testing Bad data: should never.
Data Abstraction: The Walls
Effective Java, 3rd Edition Chapter 10: Exceptions
Programming in C# Lesson 5. Exceptions..
Exception Handling Imran Rashid CTO at ManiWeber Technologies.
Java IDE Dwight Deugo Nesa Matic Portions of the notes for this lecture include excerpts from.
Introduction to Programming
SWE 619 Last modified Fall 2007 Saket Kaushik, Paul Ammann
Handling Exceptionally Sticky Problems
Effective Java, Chapter 9: Exceptions
Java Basics Exception Handling.
CMSC 202 Exceptions.
Software Construction
Defensive Programming
Presentation transcript:

Coding Defensively Coding Defensively Chapter 4 - Coder to Developer by Mike Gunderloy Instructor : Dr.James Fawcett Presented by Priyaa Nachimuthu priyaa@syr.edu

Agenda Assertions Exceptions Comments

Defensive Coding Reusable code Easy maintenance Paves way to locate problems easily Allows modifications

Assertions Problem indicators Design time debugging Assert a boolean condition Microsoft .Net runtime

Using Assertions Add a reference to System. Diagnostics namespace Use Debug. Assert method or Trace. Assert method // This method should never be called // without a source Url Debug. Assert (((d.SourceURL != string. Empty) && (d.SourceUrl != null)),”Empty SourceUrl”,”Can’t download a file unless a Source Url is supplied”);

Assertion Failed Alert

Mechanics of .Net Assertions

Debug Configuration

Release Configuration

Listener classes TraceListener – abstract class in System. Diagnostics namespace DefaultTraceListener – An object of this class is automatically added to Listeners collection of Trace and Debug classes. Writes output to output window or message boxes. TextWriterTraceListener – writes messages to any class that derives from the Stream class. EventlogTraceListener – writes messages to Windows event log. Inherit from TraceListener - custom behavior

Guidelines for good assertions Hide assertions from end – users Use Debug. Assert Assertions shouldn't have side effects // Make sure path is ok Debug. Assert ((newpath = Path.Combine(foldername,filename))!= string.Empty,”Bad path to download” ); Don’t verify compiler operation Int[] intSizes = new int[3]; Debug.Assert(intSizes.GetUpperBound(0) == 2,”Failed to initialize array “);

Guidelines for good assertions Reasonable input data Checks in the method that uses the value Check assumptions after complex code execution

Exceptions Exceptions are for exceptional situations Run-time checking public void GetDownload ( Download d ) { string filename = string.Empty; string foldername = string.Empty; WebClient wc = new WebClient(); try // code to do download } catch ( Exception e ) // bubble to any exception up to caller with custom info throw new DownloadException(“Unable to download”,d,e); Finally wc.Dispose();

Exception Mechanics try – Exception handling block catch – start of the actual exception handling finally – start of the code that will always run. Used for cleanup throw – generates an exception

Custom Exceptions There is no existing exception class that correctly represents the exceptional condition. To pass additional information to the parent code.

Guidelines for good exceptions Exceptions are for exceptional situations Use exception constructors with string value for additional information While passing error information from lower level code to higher level code use one of the constructors that accepts an Exception object. Don’t create custom exceptions when the built –ones will suffice.

Comments or Self-Documenting Code Code should be its own documentation, comments are superfluous. Well written comments make code easier to read. Writing good comments is no excuse to writing bad code.

Noise Comments Comments that make code longer with no value addition // DefaultDownloadFolder property public string DefaultDownloadFolder { // public getter get return _D; } // public setter set _D = value;

Noise Comments Formal procedure header // Procedure:GetDownload // Module: DownloadEngine.cs // Author : Mike // Creation Date: 21 October 2003 // // Inputs : // d - A Download variable with download file information // Outputs: // None // Revision History: // 05 Nov 2003 : Initial Creation // 07 Nov 2003 : Download code implemented Public void GetDownload(Download d) { // Method body goes here … }

Placeholder comments // HACK: Brute- force search, can replace this if this becomes a perf issue // TODO: Add code to make sure user has access to folder // POSTPONE : This is where we want to create custom properties Tools -> Options -> Environment -> Task List

Visual Studio.NET Task List

Summary and Intent Comments // GetDownload uses the information in a download object // to get the specified file from the internet to a local hard // drive. Any download errors are wrapped in a custom // exception and returned to the caller. Public void GetDownload(Download d) { // Method body goes here … } Summary comment public void GetDownload(Download d) try // This method should never be called // without a source Url Debug. Assert (((d.SourceURL != string. Empty) && (d.SourceUrl != null)),”Empty SourceUrl”,”Can’t download a file unless a Source Url is supplied”); catch(Exception e) // bubble to any exception up to caller with custom info throw new DownloadException(“Unable to download”,d,e);

Defensive Coding Checklist Use assertions to catch design –time errors Use exceptions to handle runtime errors Use exceptions only for exceptional situations Avoid peppering your code with noise comments Use comments as placeholders for future work Use comments to summarize and document the intent of the code When you change code, make sure to keep the comments up-to-date.