Home > Backend Development > Python Tutorial > Ask Forgiveness, Not Permission: When Is It the Better Programming Approach?

Ask Forgiveness, Not Permission: When Is It the Better Programming Approach?

Mary-Kate Olsen
Release: 2025-01-01 11:33:10
Original
799 people have browsed it

Ask Forgiveness, Not Permission: When Is It the Better Programming Approach?

Demystifying "Ask Forgiveness Not Permission"

The phrase "ask forgiveness not permission" refers to a contrast between two programming approaches: "ask for permission" and "ask forgiveness."

"Ask for Permission" Style

This approach checks for a condition before attempting an operation:

if can_do_operation():
    perform_operation()
else:
    handle_error_case()
Copy after login

However, this style has limitations:

  • In concurrent environments, conditions can change between checking and performing the operation.
  • Defining precise conditions for permission checking can be difficult.

"Ask Forgiveness" Style

This approach attempts the operation and handles any resulting errors:

try:
    perform_operation()
except Unable_to_perform:
    handle_error_case()
Copy after login

Advantages of "ask forgiveness":

  • Robustness in Concurrent Environments: It handles changes in conditions during operation.
  • Simplicity: It avoids having to define complex permission checks.

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()
Copy after login

This ensures that foo is either missing the bar field or has a valid value.

Conclusion

"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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template