当前位置:网站首页>How to write good code - Defensive Programming Guide
How to write good code - Defensive Programming Guide
2022-07-01 17:28:00 【Cloud smart aiops community】
introduction
Murphy's lawIf there are two or more ways to do something , And one of the options will lead to disaster , Someone must have made that choice . This is a pessimistic thought , Think that all bad things that may go wrong will happen . So when you have this idea to do design , It is necessary to predict the worst situation and take corresponding measures . At the same time, users do not need to think complex , You can use a system by intuition , The so-called fool proof design . Such as 3.5 Inch floppy disk design , It is designed that only one situation can be inserted .

What is defensive programming ?
Defensive programming and defensive drivingDefensive programming , This concept comes from defensive driving . In defensive driving, we should establish such a kind of thinking , That is, you can never be sure what another driver is going to do . In this way, you can ensure that you will not be hurt when others make dangerous actions . You should take the responsibility to protect yourself , Even if other drivers make mistakes .
Class Main { private Connection con = = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD); public List<Student> doQuery(String name) { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, grade, name, gender FROM students WHERE name=" + name); List<Student> studentList = new ArrayList<>(); while(rs.next()) { long id = rs.getLong(1); long grade = rs.getLong(2); String name = rs.getString(3); String gender = convertGender(rs.getInt(4)); Student student = new Student(id, grade, name, gender); studentList.add(student); } return studentList; } private String convertGender(int gender) { switch(gender) { case 0 : return "male"; case 1 : return "female"; } return null; }}
Border defense : Check all external inputs
exception handling : Choose between correctness and robustness
- Correctness means : The program never returns inaccurate results , Even if doing so will not return results or exit the program directly .
- Robustness means : The system can still operate normally under abnormal input or abnormal external environment , Even if the output result is wrong or incomplete .
Should be inspected : There is no completely reliable external environment
Show constraints : Simple and direct code style
Reduce dependence :write once, run anywhere
Silly comments
Contract programming
- precondition : It is expected that all client modules calling it will guarantee certain entry conditions , For example, non NULL、 Not 0 Other requirements ;
- Postcondition : Ensure that specific properties are given when exiting , For example, the database connection will be released when the program exits ;
- Invariant : Assume at entry that , And keep certain properties on exit .
Contractual programming is a more optimistic programming idea than defensive programming , Emphasize conventions and assertions , Students who want to know about contractual programming , You can move :https://www.eiffel.com/values/design-by-contract/introduction/
Avoid over design
summary
- Improve the quality of the project —— Reduce bug And questions ;
- Improve the readability of the source code —— The source code should become readable and understandable , And can withstand code review;
- Enable software to handle unexpected user actions through expected behavior .
appendix : Defensive programming checkList
- Whether the subroutine protects itself from harmful input data ?
- Do you use assertions to illustrate programming assumptions ? Does it include pre conditions and post conditions ?
- Whether the assertion is only used to explain what should never happen ?
- Do you specify a specific set of error handling techniques in architecture or high-level design ?
- Have you specified in the architecture or high-level design whether to make error handling more robust or correct ?
- Have you set up barriers to contain the possible damage caused by mistakes ? Whether it reduces the number of other code that needs to pay attention to error handling ?
- Did you use the auxiliary debugging code in the code ?
- If you need to enable or disable the added helper , Whether there is no need to fight ?
- Whether the amount of code mapped in defensive programming is appropriate – Not much , Not too little ?
- Is offensive programming used in the development phase to make errors difficult to ignore ?
- Have you defined a standardized exception handling scheme in the project ?
- Have you considered alternatives other than exceptions ?
- If possible , Whether the error is handled locally instead of being thrown outside as an exception ?
- Whether the code avoids throwing exceptions in constructors and destructors ?
- Whether all exceptions are at the same level of abstraction as the subroutine that threw them ?6). Whether each exception contains all the background information about the occurrence of the exception ?
- Whether there is no empty in the code catch sentence ?( Or if you use empty catch The statement is really appropriate , So is it clear ?)
- Check whether the code harmful to the input data also checks for intentional buffer overflow 、SQL Inject 、HTML Inject 、 Certificate overflow level 1 other malicious input data ?
- Whether all error return codes have been checked
- Whether all exceptions are caught ?
- Whether the information needed to help the attacker break into the system should be avoided in the error message ?
- Errors are handled more in the final product code than “ Garbage goes into , Garbage out ” It's a lot more complicated .
- Defensive programming techniques can make errors easier to detect 、 Easier to modify , And reduce the damage of errors to product code .
- Assertions can help people find mistakes as soon as possible , Especially in large-scale systems and high reliability systems , And rapidly changing code .
- The decision on how to deal with erroneous input is a key error handling decision , It is also a key high-level design decision .
- Exceptions provide an error handling method that is different from the normal flow of code . If you pay attention to abnormal use , It can be a useful supplement to programmers' knowledge toolbox , At the same time, trade-offs should also be made between exceptions and other error handling methods .
- The restrictions on product code do not apply to software under development . You can use this advantage to add code that helps you troubleshoot errors faster .
Author's brief introduction
Cloud Intelligence Architecture Department , Long term commitment to the construction and development of engineering architecture in the field of intelligent operation and maintenance , Build high performance 、 High availability 、 Highly easy to use operation and maintenance engineering framework , Raise the company's technical waterline .
Open source benefits
Cloud intelligence has become an open source data visualization platform FlyFish . By configuring the data model, it provides users with hundreds of visual graphics components , Zero coding can achieve a cool visual large screen that meets your business needs . meanwhile , Flying fish also provides flexible expansion ability , Support component development 、 Customize the configuration of functions and global events , Facing complex demand scenarios can ensure efficient development and delivery .
Click the address link below , Welcome to FlyFish Like to send Star. Participate in component development , There are ten thousand yuan in cash waiting for you to get .
- GitHub Address : https://github.com/CloudWise-...
- Gitee Address :https://gitee.com/CloudWise/f...
- Ten thousand yuan cash activities : http://bbs.aiops.cloudwise.co...
Wechat scanning identifies the QR code below , remarks 【 Flying fish 】 Join in AIOps Community flying fish developer exchange group , And FlyFish project PMC Face to face communication ~
边栏推荐
- Oom caused by improper use of multithreading
- In aks, use secret in CSI driver mount key vault
- [C language supplement] judge which day tomorrow is (tomorrow's date)
- Introduction to software engineering - Chapter 6 - detailed design
- Concatenate strings to get the result with the smallest dictionary order
- 中国超高分子量聚乙烯产业调研与投资前景报告(2022版)
- PHP implements sensitive word filtering system "suggestions collection"
- Sword finger offer II 015 All modifiers in the string
- [Verilog quick start of Niuke network question brushing series] ~ priority encoder circuit ①
- 剑指 Offer 20. 表示数值的字符串
猜你喜欢
Petrv2: a unified framework for 3D perception of multi camera images
(28) Shape matching based on contour features
Why should you consider using prism
ACM MM 2022视频理解挑战赛视频分类赛道冠军AutoX团队技术分享
机器学习11-聚类,孤立点判别
Replace UUID, nanoid is faster and safer!
Leetcode records - sort -215, 347, 451, 75
Introduction to software engineering - Chapter 6 - detailed design
换掉UUID,NanoID更快更安全!
(1) CNN network structure
随机推荐
Leetcode records - sort -215, 347, 451, 75
The amazing open source animation library is not only awesome, but also small
[C language supplement] judge which day tomorrow is (tomorrow's date)
How wild are hackers' ways of making money? CTF reverse entry Guide
判断一棵二叉树是否为平衡二叉树
单例模式的懒汉模式跟恶汉模式的区别
Code example of libcurl download file
Transition technology from IPv4 to IPv6
Radhat builds intranet Yum source server
多线程并发之CountDownLatch阻塞等待
Redis 分布式鎖
中国乙腈市场预测与战略咨询研究报告(2022版)
In aks, use secret in CSI driver mount key vault
China biodegradable plastics market forecast and investment strategy report (2022 Edition)
China sorbitol Market Forecast and investment strategy report (2022 Edition)
重磅披露!上百个重要信息系统被入侵,主机成为重点攻击目标
ShenYu 网关开发:在本地启用运行
Report on research and investment prospects of China's silicon nitride ceramic substrate industry (2022 Edition)
中国超高分子量聚乙烯产业调研与投资前景报告(2022版)
中国生物降解塑料市场预测与投资战略报告(2022版)