Coding Defensively

23
Coding Defensively Coding Defensively Coding Defensively Coding Defensively Chapter 4 - Coder to Developer by Mike Gunderloy Chapter 4 - Coder to Developer by Mike Gunderloy Instructor : Dr.James Fawcett Instructor : Dr.James Fawcett Presented by Presented by Priyaa Nachimuthu Priyaa Nachimuthu [email protected] [email protected]

description

Coding Defensively. Coding Defensively Chapter 4 - Coder to Developer by Mike Gunderloy Instructor : Dr.James Fawcett Presented by Priyaa Nachimuthu [email protected]. Agenda. Assertions Exceptions Comments. Defensive Coding. Reusable code - PowerPoint PPT Presentation

Transcript of Coding Defensively

Page 1: Coding Defensively

Coding DefensivelyCoding Defensively

Coding DefensivelyCoding Defensively Chapter 4 - Coder to Developer by Mike Chapter 4 - Coder to Developer by Mike

GunderloyGunderloy Instructor : Dr.James FawcettInstructor : Dr.James Fawcett

Presented by Presented by Priyaa NachimuthuPriyaa Nachimuthu [email protected]@syr.edu

Page 2: Coding Defensively

AgendaAgenda

►AssertionsAssertions

►ExceptionsExceptions

►CommentsComments

Page 3: Coding Defensively

Defensive CodingDefensive Coding

► Reusable code Reusable code

► Easy maintenanceEasy maintenance

► Paves way to locate problems easily Paves way to locate problems easily

► Allows modificationsAllows modifications

Page 4: Coding Defensively

AssertionsAssertions

►Problem indicatorsProblem indicators

►Design time debuggingDesign time debugging

►Assert a boolean conditionAssert a boolean condition

►Microsoft .Net runtimeMicrosoft .Net runtime

Page 5: Coding Defensively

Using AssertionsUsing Assertions► Add a reference to System. Diagnostics Add a reference to System. Diagnostics namespacenamespace

► Use Debug. Assert method or Use Debug. Assert method or Trace. Assert methodTrace. Assert method // This method should never be called // This method should never be called // without a source Url// without a source Url

Debug. Assert (((d.SourceURL != string. Empty) && Debug. Assert (((d.SourceURL != string. Empty) && (d.SourceUrl != null)),”Empty SourceUrl”,”Can’t download a (d.SourceUrl != null)),”Empty SourceUrl”,”Can’t download a file unless a Source Url is supplied”);file unless a Source Url is supplied”);

Page 6: Coding Defensively

Assertion Failed AlertAssertion Failed Alert

Page 7: Coding Defensively

Mechanics of .Net AssertionsMechanics of .Net Assertions

Configuration

DebugActive

Trace. AssertDebug. Assert

ReleaseActive

Trace. Assert

Page 8: Coding Defensively

Debug ConfigurationDebug Configuration

Page 9: Coding Defensively

Release ConfigurationRelease Configuration

Page 10: Coding Defensively

Listener classesListener classes► TraceListener – abstract class in System. Diagnostics TraceListener – abstract class in System. Diagnostics

namespacenamespace

► DefaultTraceListener – An object of this class is DefaultTraceListener – An object of this class is automatically added to Listeners collection of Trace and automatically added to Listeners collection of Trace and Debug classes. Writes output to output window or message Debug classes. Writes output to output window or message boxes.boxes.

► TextWriterTraceListener – writes messages to any class that TextWriterTraceListener – writes messages to any class that derives from the Stream class.derives from the Stream class.

► EventlogTraceListener – writes messages to Windows event EventlogTraceListener – writes messages to Windows event log.log.

► Inherit from TraceListener - custom behaviorInherit from TraceListener - custom behavior

Page 11: Coding Defensively

Guidelines for good Guidelines for good assertionsassertions

► Hide assertions from end – usersHide assertions from end – users

► Use Debug. AssertUse Debug. Assert

► Assertions shouldn't have side effectsAssertions shouldn't have side effects // Make sure path is ok// Make sure path is ok Debug. Assert ((newpath = Path.Combine(foldername,filename))!= Debug. Assert ((newpath = Path.Combine(foldername,filename))!=

string.Empty,”Bad path to download” );string.Empty,”Bad path to download” );

► Don’t verify compiler operationDon’t verify compiler operation

Int[] intSizes = new int[3];Int[] intSizes = new int[3];

Debug.Assert(intSizes.GetUpperBound(0) == 2,”Failed to initialize Debug.Assert(intSizes.GetUpperBound(0) == 2,”Failed to initialize

array “);array “);

Page 12: Coding Defensively

Guidelines for good Guidelines for good assertionsassertions

► Reasonable input dataReasonable input data

► Checks in the method that uses the Checks in the method that uses the valuevalue

► Check assumptions after complex Check assumptions after complex code code

executionexecution

Page 13: Coding Defensively

ExceptionsExceptions► Exceptions are for exceptional situationsExceptions are for exceptional situations

► Run-time checkingRun-time checking

public void GetDownload ( Download d )public void GetDownload ( Download d ) {{ string filename = string.Empty;string filename = string.Empty; string foldername = string.Empty;string foldername = string.Empty; WebClient wc = new WebClient();WebClient wc = new WebClient();

trytry {{ // code to do download// code to do download }}

catch ( Exception e )catch ( Exception e ) {{ // bubble to any exception up to caller with custom info// bubble to any exception up to caller with custom info throw new DownloadException(“Unable to download”,d,e);throw new DownloadException(“Unable to download”,d,e); }} FinallyFinally {{ wc.Dispose();wc.Dispose(); }} }}

Page 14: Coding Defensively

Exception MechanicsException Mechanics

► try – Exception handling blocktry – Exception handling block

► catch – start of the actual exception catch – start of the actual exception handlinghandling

► finally – start of the code that will always finally – start of the code that will always run. Used for cleanuprun. Used for cleanup

► throw – generates an exceptionthrow – generates an exception

Page 15: Coding Defensively

Custom ExceptionsCustom Exceptions► There is no existing exception class There is no existing exception class

that that correctly represents the exceptional correctly represents the exceptional

condition.condition.

► To pass additional information to the To pass additional information to the parent code.parent code.

Page 16: Coding Defensively

Guidelines for good exceptionsGuidelines for good exceptions► Exceptions are for exceptional situationsExceptions are for exceptional situations

► Use exception constructors with string value Use exception constructors with string value for additional informationfor additional information

► While passing error information from lower While passing error information from lower level code to higher level code use one of the level code to higher level code use one of the constructors that accepts an Exception constructors that accepts an Exception object.object.

► Don’t create custom exceptions when the Don’t create custom exceptions when the built –ones will suffice.built –ones will suffice.

Page 17: Coding Defensively

Comments or Self-Documenting Comments or Self-Documenting CodeCode

► Code should be its own documentation, Code should be its own documentation, comments are superfluous.comments are superfluous.

► Well written comments make code easier Well written comments make code easier to read.to read.

► Writing good comments is no excuse to Writing good comments is no excuse to writing bad code.writing bad code.

Page 18: Coding Defensively

Noise CommentsNoise Comments► Comments that make code longer with no Comments that make code longer with no value additionvalue addition

// DefaultDownloadFolder property// DefaultDownloadFolder propertypublic string DefaultDownloadFolderpublic string DefaultDownloadFolder{{ // public getter// public getter getget {{ return _D;return _D; }} // public setter// public setter setset {{ _D = value;_D = value; }}}}

Page 19: Coding Defensively

Noise CommentsNoise Comments► Formal procedure headerFormal procedure header

// Procedure:GetDownload// Procedure:GetDownload// Module: DownloadEngine.cs// Module: DownloadEngine.cs// Author : Mike// Author : Mike// Creation Date: 21 October 2003// Creation Date: 21 October 2003////// Inputs : // Inputs : // d - A Download variable with download file information // d - A Download variable with download file information // Outputs:// Outputs:// None// None////// Revision History:// Revision History:// 05 Nov 2003 : Initial Creation// 05 Nov 2003 : Initial Creation// 07 Nov 2003 : Download code implemented// 07 Nov 2003 : Download code implemented////

Public void GetDownload(Download d)Public void GetDownload(Download d){{ // Method body goes here// Method body goes here … … } }

Page 20: Coding Defensively

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

► Tools -> Options -> Environment -> Task ListTools -> Options -> Environment -> Task List

Page 21: Coding Defensively

Visual Studio.NET Task ListVisual Studio.NET Task List

Page 22: Coding Defensively

Summary and Intent CommentsSummary and Intent Comments► Intent commentIntent comment

// GetDownload uses the information in a download object // GetDownload uses the information in a download object // to get the specified file from the internet to a local hard // to get the specified file from the internet to a local hard // drive. Any download errors are wrapped in a custom // drive. Any download errors are wrapped in a custom // exception and returned to the caller.// exception and returned to the caller.

Public void GetDownload(Download d)Public void GetDownload(Download d){{ // Method body goes here// Method body goes here … … } }

► Summary commentSummary comment

public void GetDownload(Download d)public void GetDownload(Download d){{trytry{{ // This method should never be called // This method should never be called // without a source Url// without a source Url

Debug. Assert (((d.SourceURL != string. Empty) && (d.SourceUrl != null)),”Empty SourceUrl”,”Can’t Debug. Assert (((d.SourceURL != string. Empty) && (d.SourceUrl != null)),”Empty SourceUrl”,”Can’t download a file unless a Source Url is supplied”);download a file unless a Source Url is supplied”);

}}catch(Exception e)catch(Exception e){{ // bubble to any exception up to caller with custom info// bubble to any exception up to caller with custom info throw new DownloadException(“Unable to download”,d,e);throw new DownloadException(“Unable to download”,d,e);

}}} }

Page 23: Coding Defensively

Defensive Coding ChecklistDefensive Coding Checklist

► Use assertions to catch design –time errorsUse assertions to catch design –time errors

► Use exceptions to handle runtime errorsUse exceptions to handle runtime errors

► Use exceptions only for exceptional situationsUse exceptions only for exceptional situations

► Avoid peppering your code with noise commentsAvoid peppering your code with noise comments

► Use comments as placeholders for future workUse comments as placeholders for future work

► Use comments to summarize and document the intent of the Use comments to summarize and document the intent of the codecode

► When you change code, make sure to keep the comments When you change code, make sure to keep the comments up-to-date.up-to-date.