Defensive Programming

In defensive programming, the main idea is that if a routine is passed bad data, it won't be hurt, even if the bad dadta is another routine's fault.

Three genreal ways to handle garbage in
1. Check the values of all data from external sources.
When getting data from a file, auser, the network, or some other external interface, check to be sure that the data falls within the allowable range.
2. Check the values of all routine input parameters.
3. Decide how to handle bad inputs

Assertion
When an assertion is true, that means everything is operation as expected. When it's false, that means it has detected an unexpected error in the code.
Guidelines for Using Assertions
1. Use error handlng code for conditions you expect to occur; use assertions for conditions that should never occur.
Assertion check for conditions that should never occur. Error handling code check for off-nominal circumstances that might not occur very often, but that have been anticipated by the programmer who worte the code and that need to be handled by the production code.
2. Avoid putting executable code in assertions
Putting code into an assertion raises the possiblity that the compiler will eliminate the code when you turn off the assertion.
3. Use assertions to document perconditions and postconditions
Preconditions and postconditions are part of an approach to program design and development known as "design by contract". when preconditions and postconditions are used, each routine or class forms a contract with the rest of the program.
4. For highly robust code, assert, and then handle the error anyway.

Error Handling Techniques
1. Return a neutral value
Sometimes the best response to bad data is to continue operating and simply return a value that's known to be harmless.
2. Substitute the next piece of valid data
3. Return the same answer as the previous time.
4. Substitue the closest legal value.
5. Log a warning message to a file.
6. Return an error code
7. call an error processing routine/object.
8. Display an error message wherever the error is encountered.

Exception
1. Use exceptions to notify other parts of the program about errors that should not be ignored.
2. Throw an exception only for conditions that are truly exceptional.
3. Don't use an exception to pass the buck
If an error condition can be handled locally, handle it locally. Don't throw an uncaught exception in a section of code if you can handle the error locally.
4. Avoid throwing exception in constructors and desctructors unless you catch them in the same place.
5. Throw exceptions at the right level of abstraction.P15
6. Include all information that led to the exception in the exception message.
7. Know the exceptions your library code throws
8. Consider building a centralized exception reporter.

Thanks to your work so far, the library now has a functioning system. However, librarians have reported that some records in the CSV files are corrupted with invalid values. This has caused misbehaviour in the system, sometimes even crashing during busy exam periods, creating unnecessary stress for students. In real-world software engineering, robustness and correctness are just as important as functionality. Programs must gracefully handle unexpected situations and invalid inputs without failing. Two key approaches developers use are: Assertions: Internal checks that validate assumptions made by the programmer (e.g., "This variable should never be negative"). Assertions are mainly used during development and debugging. Defensive programming: Validates inputs and usage patterns to prevent invalid or unexpected behaviour at runtime. This includes checking for correct types, value ranges, and providing helpful error messages when something goes wrong. Description In this task, you will extend your library system by adding custom error handling to make it more robust. Python already raises built-in errors, but here you must define and use custom exceptions (in custom_errors.py) to handle library-specific error conditions. Building upon Task 3, update your user.py and book.py modules to handle invalid input, and modify task4.py to handle exceptions gracefully so that the system does not crash. You must ensure that this system is: Correct: Through use of assert to validate assumptions in your logic. Safe: Through defensive programming techniques that prevent invalid inputs (e.g. wrong types, negative amounts). In this task we will be using custom errors as python will already raise some of these errors when we execute invalid code. Our new errors are located in cusom_errors.py. You must use these custom errors, please see rubric for related penalties in this task. After auditing the CSV data, the librarian has introduced new validation rules to be applied in addition to the requirements described in Tasks 1–3. These rules strengthen data quality and prevent corrupted records from entering the system. Always include a helpful and descriptive error message when raising errors. Doing so contributes to the readability and overall quality of your assignment. Users Every user must have a password. Passwords cannot be empty. Every word in a user's name must contain only alphabetic characters. Numbers, symbols, and special characters are not allowed. Department is mandatory for students and staff, but must remain empty for other users. The only valid departments are: IT, Business, Arts, Science, Engineering, Education, Medicine and Library. Books The library only recognizes two valid book types: physical and online. The following fields are required for all books: Title, Author, Year Each book may have at most 5 keywords. Each word in keywords must consist of letters and numbers only. The only allowed special character is the hyphen (-). Loans Every loan record must be associated with an existing user and an existing book. The due date is a required field and cannot be left empty. Defensive Programming The following exceptions are provided to you in custom_errors.py: CustomTypeError: A value is the wrong type (e.g. a string instead of a float or int). CustomValueError: A value is of the correct type but invalid (e.g. negative copies). CustomDateError: Raised when a date is in the wrong format or when the date logic is invalid (e.g., borrow date occurs in the future). MissingRequiredFieldError: Raised when a required field is missing. UserNotFoundError or BookNotFoundError: Raised when a loan references a user or book that does not exist. CustomOperationError : Raised when an invalid borrow or return action is attempted. CustomLimitError: Raised when a user exceeds their quota or borrowing limit. CustomKeyError: Occurs when you try to access a key in the dictionary that doesn't exist.
最新发布
10-18
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值