当前位置:网站首页>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

边栏推荐
- [one day learning awk] function and user-defined function
- process. env. NODE_ ENV
- 表格存储中tablestore 目前支持mysql哪些函数呢?
- 搜索框和按钮缩放时会有缝隙的bug
- [target tracking] |stark
- Tensorflow team: we haven't been abandoned
- 微服务追踪SQL(支持Isto管控下的gorm查询追踪)
- Redis秒杀demo
- 求求你们,别再刷 Star 了!这跟“爱国”没关系!
- Zhang Chi Consulting: lead lithium battery into six sigma consulting to reduce battery capacity attenuation
猜你喜欢

Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results

七夕表白攻略:教你用自己的专业说情话,成功率100%,我只能帮你们到这里了啊~(程序员系列)

自动、智能、可视!深信服SSLO方案背后的八大设计

ThinkPHP kernel work order system source code commercial open source version multi user + multi customer service + SMS + email notification

Photoshop插件-HDR(二)-脚本开发-PS插件
![[pyGame practice] do you think it's magical? Pac Man + cutting fruit combine to create a new game you haven't played! (source code attached)](/img/0a/c1a4b57b9729e0cf9de1feae9f8c19.png)
[pyGame practice] do you think it's magical? Pac Man + cutting fruit combine to create a new game you haven't played! (source code attached)

她就是那个「别人家的HR」|ONES 人物

Win11如何设置用户权限?Win11设置用户权限的方法

STM32ADC模拟/数字转换详解

The newly born robot dog can walk by himself after rolling for an hour. The latest achievement of Wu Enda's eldest disciple
随机推荐
C#/VB.NET 合并PDF文档
HR面试:最常见的面试问题和技巧性答复
【IDM】IDM下载器安装
Lean Six Sigma project counseling: centralized counseling and point-to-point counseling
Pocket network supports moonbeam and Moonriver RPC layers
Deep operator overloading (2)
[每日一氵]Latex 的通讯作者怎么搞
SAP CRM organization Model(组织架构模型)自动决定的逻辑分析
Stm32f4-tft-spi timing logic analyzer commissioning record
[open source data] open source data set for cross modal (MRI, Meg, eye movement) human spatial memory research based on virtual reality scenes
idea启动Command line is too long问题处理
[stm32-usb-msc problem help] stm32f411ceu6 (Weact) +w25q64+usb-msc flash uses SPI2 to read out only 520kb
将ABAP On-Premises系统连接到中央检查系统以进行自定义代码迁移
新出生的机器狗,打滚1小时后自己掌握走路,吴恩达开山大弟子最新成果
Thinkphp内核工单系统源码商业开源版 多用户+多客服+短信+邮件通知
自动、智能、可视!深信服SSLO方案背后的八大设计
一次革命、两股力量、三大环节:《工业能效提升行动计划》背后的“减碳”路线图...
Task. Run(), Task. Factory. Analysis of behavior inconsistency between startnew() and new task()
[video memory optimization] deep learning video memory optimization method
Photoshop plug-in HDR (II) - script development PS plug-in