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.