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

边栏推荐
- 《性能之巅第2版》阅读笔记(五)--file-system监测
- Équipe tensflow: Nous ne sommes pas abandonnés
- Microservice tracking SQL (support Gorm query tracking under isto control)
- 综述 | 激光与视觉融合SLAM
- 一次革命、两股力量、三大环节:《工业能效提升行动计划》背后的“减碳”路线图...
- Zero copy technology of MySQL
- SAP s/4hana: one code line, many choices
- Smart Party Building: faith through time and space | 7.1 dedication
- TensorFlow團隊:我們沒被拋弃
- SAP S/4HANA: 一条代码线,许多种选择
猜你喜欢
RT-Thread Env 工具介绍(学习笔记)
Win11如何设置用户权限?Win11设置用户权限的方法
6.2 normalization 6.2.6 BC normal form (BCNF) 6.2.9 normalization summary
使用腾讯云搭建图床服务
【LeetCode】43. String multiplication
What is the forkjoin framework in the concurrent programming series?
Équipe tensflow: Nous ne sommes pas abandonnés
Comment win11 définit - il les permissions de l'utilisateur? Win11 comment définir les permissions de l'utilisateur
软件测试的可持续发展,必须要学会敲代码?
七夕表白攻略:教你用自己的专业说情话,成功率100%,我只能帮你们到这里了啊~(程序员系列)
随机推荐
The newly born robot dog can walk by himself after rolling for an hour. The latest achievement of Wu Enda's eldest disciple
MySQL高级篇4
How to adjust the color of the computer screen and how to change the color of the computer screen
[one day learning awk] function and user-defined function
Zhang Chi's class: several types and differences of Six Sigma data
Redis秒杀demo
使用 csv 导入的方式在 SAP S/4HANA 里创建 employee 数据
SAP S/4HANA: 一条代码线,许多种选择
Introduction to RT thread env tool (learning notes)
【OpenCV 例程200篇】216. 绘制多段线和多边形
VIM from dislike to dependence (22) -- automatic completion
[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)
周少剑,很少见
GaussDB(for MySQL) :Partial Result Cache,通过缓存中间结果对算子进行加速
6.2 normalization 6.2.6 BC normal form (BCNF) 6.2.9 normalization summary
智慧党建: 穿越时空的信仰 | 7·1 献礼
Research on manually triggering automatic decision of SAP CRM organization model with ABAP code
【显存优化】深度学习显存优化方法
Connect the ABAP on premises system to the central inspection system for custom code migration
idea启动Command line is too long问题处理