Object-Oriented Programming/Validation

This lesson introduces data validation and exception handling.

Objectives and Skills
Objectives and skills for this lesson include:
 * Validate data
 * Generate and handle exceptions
 * Use assertions to validate parameter assumptions

Readings

 * 1)  Data validation
 * 2)  Exception handling
 * 3)  Assertion (software_development)
 * 4)  Python syntax and semantics - EAFP vs. LBYL
 * 5)  Defensive programming

Multimedia

 * 1) Youtube: Using Try/Except Blocks for Error Handling in Python
 * 2) Youtube: Validation and Error Handling in Python
 * 3) Youtube: Integer and Float Input Validation with Java
 * 4) Youtube: Assertions in Python

Examples

 * C#
 * /Java/
 * /JavaScript/
 * /Python3/

Activities

 * 1) Review  Data validation. Extend the BMI main program from the previous lesson. Add input validation to ensure that only valid data may be entered for each input. Validate for both data type and range. Invalid input should terminate the program with an appropriate error message.
 * 2) Review  Parameter validation. Extend the BMI class from the previous lesson. Add parameter validation to all properties and methods to ensure that only valid parameters are passed to each method. Validate for both data type and range. Throw or raise appropriate exceptions for invalid parameters.
 * 3) Review  Assertion (software development) Extend the BMI program above. Add assertions to the main program for any assumptions not already handled by input validation. Validate for both data type and range.
 * 4) Review  Exception handling. Extend the BMI program above. Add exception handling to your main program to catch any errors thrown during processing and terminate the program gracefully.
 * 5) Update program, class, and method documentation regarding parameters and exceptions, consistent with the documentation standards for your selected programming language.

Lesson Summary

 * Data validation in computer science is the process of ensuring data have undergone data cleansing to ensure they have data quality; that is, that they are both correct and useful.


 * "Validation rules"—also know as "validation constraints" or "check routines"—are routines that check for correctness, meaningfulness, and security of data that are input to the system.


 * Data validation is intended to provide certain well-defined guarantees for fitness, accuracy, and consistency for any of various kinds of user input into an application or automated system. Failures or omissions in data validation can lead to data corruption or a security vulnerability.


 * Data-type validation is customarily carried out on one or more simple data fields. A validation process involves two distinct steps: (a) Validation Check and (b) Post-Check action.


 * Simple range and constraint validation is a test that may examine user input for consistency with a minimum/maximum range, or consistency with a test for evaluating a sequence of characters.


 * Code and cross-reference validation includes tests for data type validation, combined with one or more operations to verify that the user-supplied data is consistent with one or more external rules, requirements, or validity constraints relevant to a particular organization, context or set of underlying assumptions.


 * Structured validation allows for the combination of any of various basic data type validation steps, along with more complex processing. Such complex processing may include the testing of conditional constraints for an entire complex data object or set of process operations within a system.


 * A Validation Check uses one or more computational rules to determine if the data is valid.


 * A post-validation action sends feedback to help enforce validation.


 * Exception handling is the process of responding to the occurrence during computation of exceptions, often changing the normal flow of program execution.


 * Many computer languages have built-in support for exceptions and exception handling.


 * Exception handling in hardware is processed by the CPU. It is intended to support error detection and redirects the program flow to error handling service routines.


 * Exception handling implementation in programming languages typically involves a fair amount of support from both a code generator and the runtime system accompanying a compiler.


 * Dynamic registration generates code that continually updates structures about the program state in terms of exception handling.


 * A table-driven approach creates static tables at compile time and link time that relate ranges of the program counter to the program state with respect to exception handling.


 * Uncaught exceptions are handled by the runtime; the routine that does this is called the uncaught exception handler.


 * Dynamic checking of exceptions establishes exception handling routines that are sufficiently robust. In order to achieve this, it is necessary to present the code with a wide spectrum of invalid or unexpected inputs.


 * Python has a relatively uncluttered visual layout and uses English keywords frequently, while other languages use punctuation.


 * Python has special keywords that cannot be used as identifiers, such as,  ,  ,  , etc.


 * Python uses indentation to indicate the run of a block instead of punctuation or keywords. This makes Python syntax less robust than most other languages.


 * All variables in Python hold references to objects, and these references are passed to functions.
 * A function cannot change the value of variable references in its calling function.


 * The data types used in Python are number, string, list, tuple, and dictionary.


 * Python strings and tuples are immutable, which means that they cannot be modified after they are created.


 * Python lists, sets, and dictionaries are mutable.


 * Python sequential data types (lists, tuples, and strings) are indexed positionally.


 * Mappings, unordered types implemented in the form of dictionaries, "map" a set of immutable keys to corresponding elements.


 * The mappings between variable names (strings) and the values that the names reference are stored as dictionaries.


 * Dictionaries are directly accessible in Python.


 * Everything is an object in Python.


 * In Python, single or double quotes can be used to quote a string.


 * Interpolation can be done using the % string-format operator, the "format" method, or "f-strings".


 * Multi-line strings start and end with a series of three single or double quotes.
 * Python includes the +, -, *, /, % operators, which are executed in the usual order of operations.


 * Python uses binary comparison operators such as ==, <, and >. All numbers, strings, sequences, and mappings can be compared, and they return either  or.
 * In Python, comparison conditions are used in if statements and loops.


 * The boolean operators  and   return the value of the last operand evaluated instead of true or false.
 * An if statement is written using the keyword.


 * The  keyword can be used if the previous statement is not true and to try the next condition.
 * The  keyword executes if the previous conditions were not true.


 * Python supports two loop commands:
 * While loops are be executed as long as the statement is true.
 * For loops work like an iterator method. They iterate over a sequence, such as lists, tuples, dictionaries, sets, and strings.


 * Python is a functional programming style. Functions are first-class objects that can be created and passed around dynamically.


 * Lambda constructors contain one expression rather than statements.
 * Python supports lexical closures.
 * Variable scope is implicitly determined by the scope in which one assigns a value to the variable unless the scope is explicitly declared with  or.


 * Python supports most object-oriented programming techniques.
 * Properties allow specially defined methods to be invoked on an object instance by using the same syntax as used for attribute access.


 * Python allows the creation of class methods and static method via the use of the  and   decorators.


 * Python supports exception handling as a testing for errors in a program.
 * Single-line comments begin with the hash character and are terminated by the end of the line.


 * Decorators are a form of metaprogramming; they enhance the action of the function or method they decorate.


 * Defensive programming is an approach to improve software and source code.
 * It reduces the number of software bugs and problems.
 * It ensures that source code is readable and understandable so it is approved in a code audit.
 * It makes the software behave in a predictable manner despite unexpected inputs or user actions.


 * Secure programming is concerned with computer security, but not necessarily the safety or availability of the software. It assumes the software will be misused actively to find exploits and bugs in the code.


 * Offensive programming is a category of defensive programming. It emphasizes that certain errors should not be handled defensively.

Key Terms

 * assertion
 * A statement which is always true at that point in code execution. If the input data conflicts with the assertion statement, an assertion error is thrown.


 * catch (an exception)
 * Another word for handling an exception before it reaches runtime.


 * data cleansing
 * The process of detecting and correcting (or removing) inaccurate data from a data set.


 * data quality
 * Data have data quality if they are both correct and useful.


 * data validation
 * The process of ensuring that data have undergone data cleansing to ensure they have data quality.


 * defensive programming
 * A design technique that ensures the continuing functionality and security of a program by anticipating potential errors in execution.


 * EAFP
 * Easier to Ask for Forgiveness than Permission, an approach to error handling which tries to run a block of code and catches the exception if it fails.


 * error checking
 * Maintains the normal program flow with explicit checks for contingencies using special return variables or auxiliary global variables, as are present in some languages, in order to preemptively handle exceptions.


 * exception
 * A runtime error resulting in a change from the normal program flow.


 * exception handling
 * The process of responding to and accommodating for exceptions at or before runtime.


 * LBYL
 * Look Before You Leap, an approach to error handling which checks for possibly incorrect data or data types before executing the body of code.


 * legacy code
 * refers to an application system source code type that is no longer supported.


 * stack
 * An abstract data type which serves as a collection of elements.


 * throw or raise (an exception)
 * A mechanism to transfer control to code which can handle an exception.

C#

 * Microsoft Ignite: Exceptions and Exception Handling (C# Programming Guide)

Java

 * Assertion in Java Example | Java Assertion Tutorial

Python

 * Python.org: Using Assertions Effectively
 * Python.org: Handling Exceptions
 * Python.org: Writing Exception Classes
 * Jeff Knupp: Write Cleaner Python Using Exceptions
 * Easy Python Docs: Python Validation Examples
 * DataCamp: Exception and Error Handling in Python