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

边栏推荐
- In depth Research Report on China's disposable sanitary products production equipment industry (2022 Edition)
- (17) DAC conversion experiment
- 剑指 Offer II 105. 岛屿的最大面积
- 【牛客网刷题系列 之 Verilog快速入门】~ 优先编码器电路①
- 麦趣尔:媒体报道所涉两批次产品已下架封存,受理消费者诉求
- 拼接字符串,得到字典序最小的结果
- Redis distributed lock
- (27) Open operation, close operation, morphological gradient, top hat, black hat
- 走进微信小程序
- [C language supplement] judge which day tomorrow is (tomorrow's date)
猜你喜欢

Sword finger offer 20 String representing numeric value

英特尔开源深度学习工具库 OpenVINO,将加大与本土软硬件方合作,持续开放

There is a new breakthrough in quantum field: the duration of quantum state can exceed 5 seconds

6月刊 | AntDB数据库参与编写《数据库发展研究报告》 亮相信创产业榜单

National Security Agency (NSA) "sour Fox" vulnerability attack weapon platform technical analysis report

Redis distributed lock

(1) CNN network structure

Cookies and session keeping technology

How to use etcd to realize distributed /etc directory
![[mathematical modeling] [matlab] implementation of two-dimensional rectangular packing code](/img/de/1f572c62a0d034da9a8acb5c2f9602.jpg)
[mathematical modeling] [matlab] implementation of two-dimensional rectangular packing code
随机推荐
[Verilog quick start of Niuke network question brushing series] ~ priority encoder circuit ①
China PBAT resin Market Forecast and Strategic Research Report (2022 Edition)
Transition technology from IPv4 to IPv6
GameFramework食用指南
判断二叉树是否为二叉搜索树
在MeterSphere接口测试中如何使用JMeter函数和MockJS函数
存在安全隐患 起亚召回部分K3新能源
Redis6.0 new features
Determine whether the linked list is a palindrome linked list
How wild are hackers' ways of making money? CTF reverse entry Guide
智能运维实战:银行业务流程及单笔交易追踪
Gaussdb (for MySQL):partial result cache, which accelerates the operator by caching intermediate results
中国一次性卫生用品生产设备行业深度调研报告(2022版)
In depth Research Report on China's disposable sanitary products production equipment industry (2022 Edition)
[flask introduction series] cookies and session
美国国家安全局(NSA)“酸狐狸”漏洞攻击武器平台技术分析报告
ACL 2022 | 分解的元学习小样本命名实体识别
为什么你要考虑使用Prisma
(十六)ADC转换实验
MySQL learning summary