[Turn] Lbyl and Eafp two types of defensive programming styles

Source: Internet
Author: User

Checking the data can make the program more robust, in terms of defensive programming.
When checking the data, there are two different styles.
Lbyl:look Before you Leap
Eafp:easier to Ask forgiveness than Permission
Lbyl is checked beforehand.
Eafp is not checked, a problem is handled by exception handling.

  1. D = {}
  2. words = [' A ', 'd ',' a ',' C ',' B ',' z ',' d ']
  3. #LBYL
  4. For W in words:
  5. if w not in D:
  6. D[W] = 0
  7. D[W] + = 1
  8. #EAFP
  9. For W in words:
  10. Try:
  11. D[W] + = 1
  12. except Keyerror:
  13. D[W] = 1

Both of these styles are good or bad.
For Lbyl, it is easy to disrupt the thinking, the business logic can be done with a line of code. But there are many more lines of code to check. Defensive code, mixed with business logic, reduces readability.
With EAFP, business logic code is clearly isolated from defensive code, making it easier for developers to focus on business logic.
However, exception handling can affect a bit of performance. Because in the event of an abnormality, it is necessary to keep the scene, backtrack Traceback and so on. But in fact, the performance difference is not small, especially when the frequency of abnormal occurrence is low.
It is also important to note that if atomic operations are involved, it is strongly recommended to use the EAFP style. For example, my program logic is based on the existence of a Redis key is operating. if exists (key) is first, then do something. This becomes a 2-step operation, where the state of the key may have been changed by other threads while the multithreading is concurrent. In Eafp style, you can ensure atomicity.

[Turn] Lbyl and Eafp two types of defensive programming styles

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.