Presentation is loading. Please wait.

Presentation is loading. Please wait.

Coding Defensively Coding Defensively

Similar presentations


Presentation on theme: "Coding Defensively Coding Defensively"— Presentation transcript:

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

2 Agenda Assertions Exceptions Comments

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

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

5 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”);

6 Assertion Failed Alert

7 Mechanics of .Net Assertions

8 Debug Configuration

9 Release Configuration

10 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

11 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 “);

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

13 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();

14 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

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

16 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.

17 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.

18 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;

19 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: // Nov 2003 : Initial Creation // Nov 2003 : Download code implemented Public void GetDownload(Download d) { // Method body goes here }

20 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

21 Visual Studio.NET Task List

22 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);

23 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.


Download ppt "Coding Defensively Coding Defensively"

Similar presentations


Ads by Google