"Ask Forgiveness Not Permission": A Technical Explanation
In programming, the phrase "ask forgiveness not permission" describes two contrasting coding styles:
"Ask for Permission" Style:
if can_do_operation(): perform_operation() else: handle_error_case()
"Ask for Forgiveness" Style:
try: perform_operation() except Unable_to_perform: handle_error_case()
In the "ask for permission" approach, the presence of the can_do_operation() check prevents the perform_operation() call from executing if the operation cannot be performed. However, this approach relies on the accuracy of the can_do_operation() check, which may not always be reliable in dynamic environments or when dealing with external resources.
Benefits of "Ask for Forgiveness"
The "ask for forgiveness" style offers several benefits:
Example: Instance Attribute Access
In your example, you inquire about the use of "ask for forgiveness" when accessing instance attributes. While normally considered a programmer error, accessing a non-existent attribute can be a valid scenario, such as when dealing with optional object parts.
Instead of testing for the existence of an attribute (foo.bar) with an exception handler, it's more Pythonic to check if the attribute is not None. For optional attributes, the bar attribute is typically initialized to None initially and set to a meaningful value if available. This allows for the following test:
if foo.bar is not None: handle_optional_part(foo.bar) else: default_handling()
Conclusion
The "ask forgiveness not permission" principle recommends embracing exceptions as a natural part of program execution, particularly when dealing with optional functionality or external resource interactions. It provides greater flexibility and adaptability in dynamic and concurrent environments, while still enabling error handling through exception handling mechanisms.
The above is the detailed content of Ask Forgiveness, Not Permission: When Is Exception Handling Better Than Preemptive Checks?. For more information, please follow other related articles on the PHP Chinese website!