Defensive Programming, Assertions and Exceptions Designing Fault-Resistant Code SoftUni Team Technical Trainers Software University

Slides:



Advertisements
Similar presentations
Software Construction 1 ( ) First Semester Dr. Samer Odeh Hanna (PhD) Office: IT 327.
Advertisements

Software Quality Assurance QA Engineering, Testing, Bug Tracking, Test Automation Software University Technical Trainers SoftUni Team.
1 Defensive Programming and Debugging (Chapters 8 and 23 of Code Complete) Tori Bowman CSSE 375, Rose-Hulman September 21, 2007.
 Dimitar Ivanov Introduction to programming with microcontrollers.
C# Advanced Topics Methods, Classes and Objects SoftUni Team Technical Trainers Software University
AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
Methods Writing and using methods, overloads, ref, out SoftUni Team Technical Trainers Software University
Software University Curriculum, Courses, Exams, Jobs SoftUni Team Technical Trainers Software University
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Advanced JavaScript Course Introduction SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
Software Testing Lifecycle Exit Criteria Evaluation, Continuous Integration Ivan Yonkov Technical Trainer Software University.
Teamwork and Personal Skills Course Introduction Software University SoftUni Team Technical Trainers.
Fundamentals SoftUni Welcome to Software University SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Conditional Statements Implementing Control-Flow Logic in C# SoftUni Team Technical Trainers Software University
Loops Repeating Code Multiple Times SoftUni Team Technical Trainers Software University
How to Design Error Steady Code Ivaylo Bratoev Telerik Corporation
Database APIs and Wrappers
Svetlin Nakov Technical Trainer Software University
Build Processes and Continuous Integration Automating Build Processes Software University Technical Trainers SoftUni Team.
Introduction to Exception Handling and Defensive Programming.
Unit Testing Building Rock-Solid Software SoftUni Team Technical Trainers Software University
Test-Driven Development Learn the "Test First" Approach to Coding SoftUni Team Technical Trainers Software University
Defining Classes Classes, Fields, Constructors, Methods, Properties SoftUni Team Technical Trainers Software University
Static Members and Namespaces Static Members, Indexers, Operators, Namespaces SoftUni Team Technical Trainers Software University
CV Structure, Content, Layout, Formatting, Best Practices SoftUni Team Technical Trainers Software University
Controllers and Markup Controllers, $scope, Markup, Directives, Expressions, Binding, Filters, Validation SoftUni Team Technical Trainers Software University.
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Asynchronous Web Services Writing Asynchronous Web Services SoftUni Team Technical Trainers Software University
Defensive Programming, Assertions and Exceptions Designing Error Steady Code SoftUni Team Technical Trainers Software University
C# Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Learn to Design Error Steady Code Svetlin Nakov Telerik Software Academy academy.telerik.com Technical Trainer
Exam Preparation Algorithms Course: Sample Exam SoftUni Team Technical Trainers Software University
Exception Handling Handling Errors During the Program Execution SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability Svetlin Nakov Technical Trainer Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Design Patterns: Structural Design Patterns General and reusable solutions to common problems in software design Software University
Advanced C# Course Introduction SoftUni Team Technical Trainers Software University
Prototype Chain and Inheritance Prototype chain, Inheritance, Accessing Base Members Software University Technical Trainers SoftUni Team.
Events Event Handling in JavaScript SoftUni Team Technical Trainers Software University
Object-Oriented Programming Course Introduction Svetlin Nakov Technical Trainer Software University
Reflection Programming under the hood SoftUni Team Technical Trainers Software University
Mocking with Moq Tools for Easier Unit Testing SoftUni Team Technical Trainers Software University
Operators and Expressions
Design Patterns: Behavioral Design Patterns General and reusable solutions to common problems in software design Software University
Mocking Unit Testing Methods with External Dependencies SoftUni Team Technical Trainers Software University
Mocking with Moq Mocking tools for easier unit testing Svetlin Nakov Technical Trainer Software University
PHP Exception Handling How to handle and create user-defined exceptions Mario Peshev Technical Trainer Software University
Test-Driven Development Learn the "Test First" Approach to Coding Svetlin Nakov Technical Trainer Software University
Sets, Dictionaries SoftUni Team Technical Trainers Software University
High-Quality Code: Course Introduction Course Introduction SoftUni Team Technical Trainers Software University
Advanced Tree Structures Binary Trees, AVL Tree, Red-Black Tree, B-Trees, Heaps SoftUni Team Technical Trainers Software University
PHP Basics Course Introduction Svetlin Nakov Technical Trainer Software University
Functional Programming Data Aggregation and Nested Queries Ivan Yonkov Technical Trainer Software University
Programming Fundamentals Course Introduction SoftUni Team Technical Trainers Software University
Doctrine The PHP ORM SoftUni Team Technical Trainers Software University
Creating Content Defining Topic, Creating Technical Training Materials SoftUni Team Technical Trainers Software University
ASP.NET MVC Course Program, Trainers, Evaluation, Exams, Resources SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
Inheritance Class Hierarchies SoftUni Team Technical Trainers Software University
Stacks and Queues Processing Sequences of Elements SoftUni Team Technical Trainers Software University
Generics SoftUni Team Technical Trainers Software University
Asynchronous Programming Writing Asynchronous Code in Java SoftUni Team Technical Trainers Software University
High-Quality Programming Code Code Correctness, Readability, Maintainability, Testability, Etc. SoftUni Team Technical Trainers Software University
Mocking tools for easier unit testing
Defensive Programming
Software Construction
Software Construction
Presentation transcript:

Defensive Programming, Assertions and Exceptions Designing Fault-Resistant Code SoftUni Team Technical Trainers Software University

Table of Contents 1.What is Defensive Programming?  How to Handle Errors? 2.Assertions and Debug.Assert(…) 3.Exceptions Handling Principles 4.Error Handling Strategies 2

Defensive Programming Using Assertions and Exceptions Correctly

4  Defensive programming is similar to defensive driving  You are never sure what other drivers will do  What to handle correctly?  Unusual execution flow, unusual situations, incorrect input and state What is Defensive Programming? Expect incorrect input and handle it correctly

5  The "garbage in  garbage out" pattern is wrong!  Garbage in  exception out / error message out / no garbage allowed in / null value out  Data validation principle  Check the values of all data from external sources  From user, file, internet, DB, etc. Protecting against Invalid Input

6  Check the values of all routine input parameters  Decide how to handle bad input  Return a neutral value, e. g. null  Substitute with valid data  Throw an exception, e.g. throw new ArgumentException(…)  Show an error message, e.g. a balloon in the UI  Log an error message and stop the application (e. g. unhandled exception) Protecting against Invalid Input (2)

Assertions Checking Preconditions and Postconditions

8  Assertion – a check statement placed in the code, that must always be true at that moment of execution  Assertions are used during development  Removed in the release builds  Assertions check for bugs in the code Assertions public double GetAverageStudentGrade() { Debug.Assert(studentGrades.Count > 0, "Student grades not initialized!"); Debug.Assert(studentGrades.Count > 0, "Student grades not initialized!"); return studentGrades.Average(); return studentGrades.Average();}

9  Use assertions for conditions that should never occur in practice  Failed assertion indicates a fatal error in the program  usually unrecoverable  Use assertions to document assumptions made in the code (preconditions & postconditions) Assertions (2) private Student GetRegisteredStudent(int id) { Debug.Assert(id > 0); // precondition check Debug.Assert(id > 0); // precondition check Student student = registeredStudents[id]; Student student = registeredStudents[id]; Debug.Assert(student.IsRegistered); // postcondition check Debug.Assert(student.IsRegistered); // postcondition check}

10  Avoid putting executable code in assertions  PerformAction() won't be invoked in production. Better use:  Assertions should fail loudly  Assertion fail == fatal error  total crash  Assertions are supported in most languages: C#, Java, PHP, …  Debug.Assert(condition, message) in C# Assertions (3) Debug.Assert(PerformAction(), "Could not perform action"); bool actionPerformed = PerformAction(); Debug.Assert(actionPerformed, "Could not perform action");

Assertions Live Demo

Exceptions Best Practices for Exception Handling

13  Exceptions provide a way to inform the caller about an error or exceptional events  Can be caught and processed by the callers  Methods can throw exceptions: Exceptions public void ReadInput(string input) { if (input == null) if (input == null) { throw new ArgumentNullException( "Input string cannot be null."); } throw new ArgumentNullException( "Input string cannot be null."); } …}

14  Use the try-catch statement to handle exceptions:  You can use multiple catch blocks to for different exception types  Unhandled exceptions propagate to the caller over the stack Exceptions (2) void PlayNextTurn() { try try { readInput(input); readInput(input); … } catch (ArgumentException e) catch (ArgumentException e) { Console.WriteLine("Invalid argument!"); Console.WriteLine("Invalid argument!"); }} Exception thrown here The code here will not be executed

15  Use finally block to execute code even if exception occurs:  Perfect place to perform cleanup for any resources allocated in the try block Exceptions (3) void PlayNextTurn() { try try { … } … } finally finally { Console.WriteLine("Hello from finally!"); Console.WriteLine("Hello from finally!"); }} Exceptions can be eventually thrown here This code will always be executed

16  Use exceptions to notify the other parts of the program about errors / problematic situations  Errors that should not be ignored  Throw an exception only for conditions that are truly exceptional  Should I throw an exception when I check for user name and password?  better return false  Don't use exceptions as control flow mechanisms Exceptions (4)

17  Throw exceptions at the right level of abstraction Exceptions (5) class Employee { … public TaxId public TaxId { get { throw new JsonUnserializeException(…); } { get { throw new JsonUnserializeException(…); }} class Employee { … public TaxId public TaxId { get { throw new EmployeeDataNotAvailable(…); } { get { throw new EmployeeDataNotAvailable(…); }}

18  Use descriptive error messages  Incorrect example:  Example:  Avoid empty catch blocks Exceptions (6) throw new Exception("Error!"); throw new ArgumentOutOfrangeException("The speed should be a number" + "between " + MinSpeed + " and " + MaxSpeed + "."); try{ …} catch (Exception ex) { }

19  Always include the exception cause when throwing a new exception Exceptions (7) try{ WithdrawMoney(account, amount); WithdrawMoney(account, amount);} catch (DatabaseException dbex) { throw new WithdrawException(String.Format( throw new WithdrawException(String.Format( "Can not withdraw the amount {0} from account {1}", "Can not withdraw the amount {0} from account {1}", amount, account), dbex); amount, account), dbex);} We chain the original exception (the source of the problem)

20  Catch only exceptions that you are capable to process correctly  Do not catch all exceptions!  Incorrect example:  What about OutOfMemoryException ? Exceptions (8) try{ ReadSomeFile(); ReadSomeFile();}catch{ Console.WriteLine("File not found!"); Console.WriteLine("File not found!");}

21  Have an exception handling strategy for all unexpected / unhandled exceptions:  Consider logging (e.g. Log4Net)  Show end users only messages that they could understand Exceptions (9) or

Exceptions Live Demo ILSpy Decompiling using ILSpy

Error Handling Strategies Assertions vs. Exceptions vs. Other Techniques

24  How to handle errors that you expect to occur?  Throw an exception (in OOP)  Return a neutral value, e.g. -1 in IndexOf(…)  Substitute the next piece of valid data (e.g. file)  Return the same answer as the previous time  Substitute the closest legal value  Return an error code (in old languages / APIs)  Display an error message in the UI  Call method / log a warning message  Crash / shutdown / reboot Error Handling Techniques

25  Exceptions are notifications about error condition or unusual event  Inform the caller about error or exceptional event  Can be caught and application can continue working  Assertions are fatal errors  Failed assertions always indicate bugs in the code  Can not be caught and processed  Application can't continue in case of failed assertion  When in doubt  throw an exception Assertions vs. Exceptions

26  Assertions are rarely used in C#  In C# prefer throwing an exception when the input data / internal object state are invalid  Instead of checking preconditions  Prefer unit testing to test the code  Instead of checking postconditions  You may use assertions to aid debugging  To make sure the code always does what it is meant to do (the internal state of the application is valid) Assertions in C#

27  Choose your error handling strategy and follow it consistently  Assertions / exceptions / error codes / other  In C#,.NET and OOP prefer using exceptions  Assertions are rarely used, only as additional checks for fatal error  Throw an exception for incorrect input / incorrect object state / invalid operation  In other environments you can use error codes  For example, SQL errors or HTTP status codes Error Handling Strategy

28  How will you handle an error while calculating single pixel color in a computer game?  How will you handle error in financial software? Can you afford to lose money?  Correctness == never returning wrong result  Try to achieve correctness as a primary goal  Robustness == always trying to do something that will allow the software to keep running  Use as last resort, for non-critical errors Robustness vs. Correctness

29 Assertions vs. Exceptions public string Substring(string str, int startIndex, int length) { if (str == null) if (str == null) { throw new NullReferenceException("The input string is null."); throw new NullReferenceException("The input string is null."); } if (startIndex >= str.Length) if (startIndex >= str.Length) { throw new ArgumentException("Invalid startIndex:" + startIndex); throw new ArgumentException("Invalid startIndex:" + startIndex); } if (startIndex + count > str.Length) if (startIndex + count > str.Length) { throw new ArgumentException("Invalid length:" + length); throw new ArgumentException("Invalid length:" + length); } … Debug.Assert(result.Length == length); Debug.Assert(result.Length == length);} Check the input and preconditions Perform the method's main logic Check the postconditions

30  Barricade your program to stop the damage caused by incorrect data  Consider same approach for class design  Public methods  validate the data  Private methods  you may assume the data is safe  Consider using exceptions for public methods and assertions for private methods Error Barricades public methods private methods safe data

31  Too much defensive programming is not good  Strive for balance  How much defensive programming to leave in production code?  Remove the code that results in hard crashes  Leave in code that checks for important errors  Log errors for your technical support personnel  See that the error messages you show are user-friendly Being Defensive About Defensive Programming

Defensive Programming, Assertions and Exceptions Exercises in Class

33 1.Defensive Programming 2.Assertions and Exceptions  Use exceptions to validate preconditions on input data  Use assertions to validate postconditions  Use unit tests in addition to assertions to ensure the code behaves correctly 3.Error Handling Strategies and Best Practices  Correctness vs. Robustness Summary

? ? ? ? ? ? ? ? ? Defensive Programming, Assertions and Exceptions

License  This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" licenseCreative Commons Attribution- NonCommercial-ShareAlike 4.0 International 35  Attribution: this work may contain portions from  "Fundamentals of Computer Programming with C#" book by Svetlin Nakov & Co. under CC-BY-SA licenseFundamentals of Computer Programming with C#CC-BY-SA  "C# Part I" course by Telerik Academy under CC-BY-NC-SA licenseC# Part ICC-BY-NC-SA

Free Software University  Software University Foundation – softuni.orgsoftuni.org  Software University – High-Quality Education, Profession and Job for Software Developers  softuni.bg softuni.bg  Software Facebook  facebook.com/SoftwareUniversity facebook.com/SoftwareUniversity  Software YouTube  youtube.com/SoftwareUniversity youtube.com/SoftwareUniversity  Software University Forums – forum.softuni.bgforum.softuni.bg