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


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


  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


+ absolute_zero_celsius: float {read only}
+ absolute_zero_fahrenheit: float {read only}
+ celsius: float
+ fahrenheit: float
+ Temperature(celsius: float = None,
    fahrenheit: float = None)
+ to_celsius(fahrenheit: float)
+ to_fahrenheit(celsius: float)
- validate_celsius(celsius: float)
- validate_fahrenheit(fahrenheit: float)


+ bmi: float {read only}
+ feet: float
+ inches: float
+ kilograms: float
+ meters: float
+ pounds: float
+ BMI(feet: float = 0, inches: float = 0,
    kilograms: float = 0, meters: float = 0,
    pounds: float = 0)
+ calculate_metric(kilograms: float, meters: float)
+ calculate_us(pounds: float, feet: float, inches: float)
- feet_to_inches(feet: float)
- inches_to_meters(inches: float)
- pounds_to_kilograms(pounds: float)
- validate_float(value: float, minimum: float, maximum: float)
  1. Review Wikipedia: 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 Wikipedia: 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 Wikipedia: 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 Wikipedia: 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.[1]
  • "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.[2]
  • 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.[3]
  • 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.[4]
  • 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.[5]
  • 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.[6]
  • 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.[7]
  • A Validation Check uses one or more computational rules to determine if the data is valid.[8]
  • A post-validation action sends feedback to help enforce validation.[9]
  • Exception handling is the process of responding to the occurrence during computation of exceptions, often changing the normal flow of program execution.[10]
  • Many computer languages have built-in support for exceptions and exception handling.[11]
  • 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.[12]
  • 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.[13]
  • Dynamic registration generates code that continually updates structures about the program state in terms of exception handling. [14]
  • 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.[15]
  • Uncaught exceptions are handled by the runtime; the routine that does this is called the uncaught exception handler.[16]
  • 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.[17]
  • Python has a relatively uncluttered visual layout and uses English keywords frequently, while other languages use punctuation.[18]
  • Python has special keywords that cannot be used as identifiers, such as and, assert, class, break, etc.[19]
  • 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.[20]
  • All variables in Python hold references to objects, and these references are passed to functions.[21]
    • A function cannot change the value of variable references in its calling function.[22]
  • The data types used in Python are number, string, list, tuple, and dictionary.[23]
  • Python strings and tuples are immutable, which means that they cannot be modified after they are created.[24]
  • Python lists, sets, and dictionaries are mutable.[25]
  • Python sequential data types (lists, tuples, and strings) are indexed positionally.[26]
  • Mappings, unordered types implemented in the form of dictionaries, "map" a set of immutable keys to corresponding elements.[27]
  • The mappings between variable names (strings) and the values that the names reference are stored as dictionaries.[28]
  • Dictionaries are directly accessible in Python.[29]
  • Everything is an object in Python.[30]
  • In Python, single or double quotes can be used to quote a string.[31]
  • Interpolation can be done using the % string-format operator, the "format" method, or "f-strings".[32]
  • Multi-line strings start and end with a series of three single or double quotes.[33]
  • Python includes the +, -, *, /, % operators, which are executed in the usual order of operations.[34]
  • Python uses binary comparison operators such as ==, <, and >. All numbers, strings, sequences, and mappings can be compared, and they return either True or False.[35]
  • In Python, comparison conditions are used in if statements and loops.[36]
  • The boolean operators and and or return the value of the last operand evaluated instead of true or false.[37]
  • An if statement is written using the keyword if.[38]
  • The elif keyword can be used if the previous statement is not true and to try the next condition.[39]
  • The else keyword executes if the previous conditions were not true.[40]
  • Python supports two loop commands:[41]
    • While loops are be executed as long as the statement is true.[42]
    • For loops work like an iterator method. They iterate over a sequence, such as lists, tuples, dictionaries, sets, and strings.[43]
  • Python is a functional programming style. Functions are first-class objects that can be created and passed around dynamically.[44]
  • Lambda constructors contain one expression rather than statements.[45]
  • Python supports lexical closures.[46]
    • Variable scope is implicitly determined by the scope in which one assigns a value to the variable unless the scope is explicitly declared with global or nonlocal.[47]
  • Python supports most object-oriented programming techniques.[48]
  • Properties allow specially defined methods to be invoked on an object instance by using the same syntax as used for attribute access.[49]
  • Python allows the creation of class methods and static method via the use of the @classmethod and @staticmethod decorators.[50]
  • Python supports exception handling as a testing for errors in a program.[51]
  • Single-line comments begin with the hash character (#) and are terminated by the end of the line.[52]
  • Decorators are a form of metaprogramming; they enhance the action of the function or method they decorate.[53]
  • Defensive programming is an approach to improve software and source code.[54]
    • It reduces the number of software bugs and problems.[55]
    • It ensures that source code is readable and understandable so it is approved in a code audit.[56]
    • It makes the software behave in a predictable manner despite unexpected inputs or user actions.[57]
  • 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. [58]
  • Offensive programming is a category of defensive programming. It emphasizes that certain errors should not be handled defensively.[59]

Key Terms

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.[60]
catch (an exception)
Another word for handling an exception before it reaches runtime.[61]
data cleansing
The process of detecting and correcting (or removing) inaccurate data from a data set.[62]
data quality
Data have data quality if they are both correct and useful.[63]
data validation
The process of ensuring that data have undergone data cleansing to ensure they have data quality.[64]
defensive programming
A design technique that ensures the continuing functionality and security of a program by anticipating potential errors in execution.[65]
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.[66]
error checking[67]
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.[68]
A runtime error resulting in a change from the normal program flow.[69]
exception handling
The process of responding to and accommodating for exceptions at or before runtime.
Look Before You Leap, an approach to error handling which checks for possibly incorrect data or data types before executing the body of code.[70]
legacy code
refers to an application system source code type that is no longer supported. [71]
An abstract data type which serves as a collection of elements.[72]
throw or raise (an exception)
A mechanism to transfer control to code which can handle an exception.[73]

See Also







  1. Wikipedia: Data validation
  2. Wikipedia: Data validation
  3. Wikipedia: Data validation
  4. Wikipedia: Data validation
  5. Wikipedia: Data validation
  6. Wikipedia: Data validation
  7. Wikipedia: Data validation
  8. Wikipedia: Data validation
  9. Wikipedia: Data validation
  10. Wikipedia: Exception handling
  11. Wikipedia: Exception handling
  12. Wikipedia: Exception handling
  13. Wikipedia: Exception handling
  14. Wikipedia: Exception handling
  15. Wikipedia: Exception handling
  16. Wikipedia: Exception handling
  17. Wikipedia: Exception handling
  18. Wikipedia: Python syntax and semantics
  19. Wikipedia: Python syntax and semantics
  20. Wikipedia: Python syntax and semantics
  21. Wikipedia: Python syntax and semantics
  22. Wikipedia: Python syntax and semantics
  23. Wikipedia: Python syntax and semantics
  24. Wikipedia: Python syntax and semantics
  25. Wikipedia: Python syntax and semantics
  26. Wikipedia: Python syntax and semantics
  27. Wikipedia: Python syntax and semantics
  28. Wikipedia: Python syntax and semantics
  29. Wikipedia: Python syntax and semantics
  30. Wikipedia: Python syntax and semantics
  31. Wikipedia: Python syntax and semantics
  32. Wikipedia: Python syntax and semantics
  33. Wikipedia: Python syntax and semantics
  34. Wikipedia: Python syntax and semantics
  35. Wikipedia: Python syntax and semantics
  36. Wikipedia: Python syntax and semantics
  37. Wikipedia: Python syntax and semantics
  38. Wikipedia: Python syntax and semantics
  39. Wikipedia: Python syntax and semantics
  40. Wikipedia: Python syntax and semantics
  41. Wikipedia: Python syntax and semantics
  42. Wikipedia: Python syntax and semantics
  43. Wikipedia: Python syntax and semantics
  44. Wikipedia: Python syntax and semantics
  45. Wikipedia: Python syntax and semantics
  46. Wikipedia: Python syntax and semantics
  47. Wikipedia: Python syntax and semantics
  48. Wikipedia: Python syntax and semantics
  49. Wikipedia: Python syntax and semantics
  50. Wikipedia: Python syntax and semantics
  51. Wikipedia: Python syntax and semantics
  52. Wikipedia: Python syntax and semantics
  53. Wikipedia: Python syntax and semantics
  54. Wikipedia: Defensive programming
  55. Wikipedia: Defensive programming
  56. Wikipedia: Defensive programming
  57. Wikipedia: Defensive programming
  58. Wikipedia: Defensive programming
  59. Wikipedia: Defensive programming
  60. Wikipedia: Assertion (software development)
  61. Wikipedia: Exception handling
  62. Wikipedia: Data cleansing
  63. Wikipedia: Data validation
  64. Wikipedia: Data validation
  65. Wikipedia: Defensive programming
  66. Wikipedia: Python syntax and semantics
  67. Wikipedia: Exception handling
  68. Wikipedia: Exception handling
  69. Wikipedia: Exception handling
  70. Wikipedia: Python syntax and semantics
  71. Wikipedia: Defensive programming
  72. Wikipedia: Stack (abstract data type)
  73. Wikipedia: Exception handling
  74. BillWagner. "Exceptions and Exception Handling - C# Programming Guide". docs.microsoft.com. Retrieved 2020-09-18.