The phrase "ask forgiveness not permission" refers to a contrast between two programming approaches: "ask for permission" and "ask forgiveness."
This approach checks for a condition before attempting an operation:
if can_do_operation(): perform_operation() else: handle_error_case()
However, this style has limitations:
This approach attempts the operation and handles any resulting errors:
try: perform_operation() except Unable_to_perform: handle_error_case()
Advantages of "ask forgiveness":
Application to Object Properties
In your example, the property foo.bar should not be considered a failure of the foo object if it does not exist. Rather, it is typically a programming error. To handle this, initialize bar to None and use:
if foo.bar is not None: handle_optional_part(foo.bar) else: default_handling()
This ensures that foo is either missing the bar field or has a valid value.
"Ask forgiveness not permission" is not about excusing poor coding. Rather, it is about prioritizing robustness and clarity in exceptional situations where operations may fail. In the case of optional object properties, representing them with a None default value and using proper existence checks follows this principle.
The above is the detailed content of Ask Forgiveness, Not Permission: When Is It the Better Programming Approach?. For more information, please follow other related articles on the PHP Chinese website!