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.
- D = {}
- words = [' A ', 'd ',' a ',' C ',' B ',' z ',' d ']
- #LBYL
- For W in words:
- if w not in D:
- D[W] = 0
- D[W] + = 1
- #EAFP
- For W in words:
- Try:
- D[W] + = 1
- except Keyerror:
- 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