当前位置:网站首页>How to write good code - Defensive Programming Guide
How to write good code - Defensive Programming Guide
2022-07-01 15:57:00 【InfoQ】
introduction

What is defensive programming ?
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 .
Avoid over design
- Prevent impossible mistakes , As above case Shown , For the results returned by the database , use rs.next() You can judge whether there is value , It doesn't need to be right rs Carry out non null Judge ;
- Too much defensive code , It will make the whole program appear bloated 、 Difficult to maintain , The code is full of judgment and non business code ; The performance of the program will also be affected ;
- When there are a lot of exception catching and handling in the code , It may cause the abnormality to be swallowed , Not reported normally .
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
Open source benefits
- GitHub Address : https://github.com/CloudWise-OpenSource/FlyFish
- Gitee Address :https://gitee.com/CloudWise/fly-fish
- Ten thousand yuan cash activities : http://bbs.aiops.cloudwise.com/t/Activity

边栏推荐
- 电脑屏幕变色了怎么调回来,电脑屏幕颜色怎么改
- [open source data] open source data set for cross modal (MRI, Meg, eye movement) human spatial memory research based on virtual reality scenes
- 2022 Moonriver全球黑客松优胜项目名单
- Zhang Chi Consulting: lead lithium battery into six sigma consulting to reduce battery capacity attenuation
- 药品溯源夯实安全大堤
- Advanced cross platform application development (24): uni app realizes file download and saving
- 她就是那个「别人家的HR」|ONES 人物
- 自動、智能、可視!深信服SSLO方案背後的八大設計
- Pico,能否拯救消费级VR?
- 【显存优化】深度学习显存优化方法
猜你喜欢
随机推荐
ADS算力芯片的多模型架构研究
Description | Huawei cloud store "commodity recommendation list"
The latest NLP game practice summary!
SAP s/4hana: one code line, many choices
自動、智能、可視!深信服SSLO方案背後的八大設計
ABAP-屏幕切换时,刷新上一个屏幕
vim 从嫌弃到依赖(22)——自动补全
表格存储中tablestore 目前支持mysql哪些函数呢?
[video memory optimization] deep learning video memory optimization method
【Pygame实战】你说神奇不神奇?吃豆人+切水果结合出一款你没玩过的新游戏!(附源码)
Pico, can we save consumer VR?
6.2 normalization 6.2.6 BC normal form (BCNF) 6.2.9 normalization summary
[cloud trend] new wind direction in June! Cloud store hot list announced
【显存优化】深度学习显存优化方法
2023届春招实习-个人面试过程和面经分享
Lean Six Sigma project counseling: centralized counseling and point-to-point counseling
SAP S/4HANA: 一条代码线,许多种选择
TensorFlow团队:我们没被抛弃
DO280管理应用部署--pod调度控制
Seata中1.5.1 是否支持mysql8?









