当前位置:网站首页>I was tortured by my colleague's null pointer for a long time, and finally learned how to deal with null pointer
I was tortured by my colleague's null pointer for a long time, and finally learned how to deal with null pointer
2022-07-04 04:06:00 【Java geek Technology】
A fan has been employed for so long , In any case, I wouldn't expect to be tortured to death by a null pointer returned by an interface written by my colleagues , Tortured to death , But I don't know why , Have you ever had such an experience ?
NullPointerException
The title is eye-catching , To tell you , This null pointer is abnormal , Tell the truth , Many of them are easy to solve in the project , But sometimes the cause of problems is something you can't think of , It's like this .
The front-end code is as follows :
var setting = {
url:"findFileById",
data:{
id:id
},
success:function (data) {
console.log(data);
},
error:function (data) {
console.log(" Abnormal query file ")
}
}
ajax(setting);
ajax Here is just a package
function ajax(setting) {
$.ajax({
type:"post",
url:setting.url+".do",
dataType:setting.dataType||"json",
contentType:"application/json;utf-8",
data:JSON.stringify(setting.data)||{},
async:setting.async,
success:function (data) {
setting.success(data);
},
error:function (data) {
setting.error(" Interface error , Please try again ");
}
})
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
The background business processing is as follows :
@PostMapping("findFileById")
@ResponseBody
public File findFileById(HttpServletRequest request, HttpServletResponse response, @RequestBody Map < String,Object > map){
return deliverFileService.findFileById(request,map);
}
- 1.
- 2.
- 3.
- 4.
- 5.
I'm sure you'll say , You can't do such a simple thing , What do you eat, fan , There is a problem with every query file , As a matter of fact , In the code, my colleagues did not completely deal with the problem of null value , The result has been ajax There is “ Interface error , Please try again ” Error of .
The problem is that he doesn't process empty data , And directly returned to me , This kind of problem is also very strange , Many times, it is not necessary to deal with empty data to prevent NULL Is it abnormal ? And ah fan also found him at the first time , He said no problem , Call normally from him , I was embarrassed at that time , The parameters I passed you are ok , If the query data is empty , There should be a prompt . So ah fan can only simply modify his code , Turned into
@PostMapping("findFileById")
@ResponseBody
public File findFileById(HttpServletRequest request, HttpServletResponse response, @RequestBody Map < String,Object > map){
return deliverFileService.findFileById(request,map)!= null ?deliverFileService.findFileById(request,map) : new ; new DeliverFile();
}
- 1.
- 2.
- 3.
- 4.
- 5.
A fan can't make too big changes to him , It can only be called here if it is null When , Just return me an empty object , If not , Just return the queried data to me .
Now let's talk about how to deal with our null value , Otherwise, if you write a data interface in the future , Call others , If the call is an empty string, it's just , But if it looks like null This kind of thing that is not handled , Then you will be despised by others .
How to deal with null pointer exceptions
When will it appear NullPointerException?
We all know NullPointerException It's inheritance RuntimeException Of , That is, the abnormal information will appear when running , When we write code , If the code is running , When the object we use is not initialized , Or when it is empty , There will be an exception of null pointer , And this anomaly is what we feel most Low Of , The most unlikely exception , But often because of their own inattention , And that's what happened .
In fact, there are too many ways , And many times we don't pay attention to this matter , For example, object , Empty operation , But if you judge empty when using each object , Then your code will really appear :
if(a!=null){
if(b!=null){
if(c!=null){
....
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
When you see this code , The first feeling is whether you directly want to pull this friend over and beat him , If you write too much , People are going crazy , Especially the secondary maintenance personnel .
In fact, although this method is stupid , But it's also a habit , Sentenced to empty , Functionally , Surely there won't be a lot of trouble , But such a null value is also very painful , Then let's deal with him .
1. Let's not talk about this. Just judge whether the object is empty .
the second , Just compare equals Method time , This is our writing habit many times
if(text.equals("xxxxx")){
}
- 1.
- 2.
- 3.
In fact, there is no problem with this comparison , But have you ever thought about it , If you say your text It's empty ? When you compare, you make mistakes ? And once an interviewer asked me , Why write the known string in front of the written test question , Maybe it was just a habit at that time , But later I found it was really useful .
You change to :
if("xxxxx".equals(text)){
}
- 1.
- 2.
- 3.
The error of null pointer will be avoided , What a good habit, isn't it ?
Third , We are also in Java8 Features provided inside Optional
ofNullable, Namely Optional Provided in , Pass the parameters we need , You can judge whether it is empty .
And for sets , You can use the method modified before , Judge whether it is null, If it is null, Then we must return an empty object , Or an empty set , For those who call your interface later , Also very friendly .
I know many people will say , Then I'll write a comment on the interface , The value returned by the query may be empty , Please call carefully , Although you prompted the question , But you are not solving the problem , Equivalent to , You threw out all the anomalies , Instead of dealing with him .
We can also use Java8 Provided in Optional , Like this
Optional < Product >getProductOptional(String id)
- 1.
This is the time , When our caller knows there is Optional In the presence of , Naturally understand .
About handling null, Do you have any other good ways ?
边栏推荐
- Msgraphmailbag - search only driveitems of file types
- The maximum expiration time of client secret in azure ad application registration is modified to 2 years
- 华为云鲲鹏工程师培训(广西大学)
- Graduation summary
- Tcpclientdemo for TCP protocol interaction
- CSP drawing
- SQL語句加强練習(MySQL8.0為例)
- [paddleseg source code reading] paddleseg custom data class
- Infiltration practice guest account mimikatz sunflower SQL rights lifting offline decryption
- 新型数据中心,助力加快构建以数据为关键要素的数字经济
猜你喜欢
JVM family -- heap analysis
Mindmanager2022 efficient and easy to use office mind map MindManager
Balance between picture performance of unity mobile game performance optimization spectrum and GPU pressure
'2'&gt;' 10'==true? How does JS perform implicit type conversion?
LNK2038 检测到“RuntimeLibrary”的不匹配项: 值“MD_DynamicRelease”不匹配值“MDd_DynamicDebug”(main.obj 中)
如何有效远程办公之我见 | 社区征文
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
ctf-pikachu-XSS
Go 语言入门很简单:Go 实现凯撒密码
Storage of MySQL database
随机推荐
“软硬皆施”,助力建成新型云计算数据中心
Mitsubishi M70 macro variable reading Mitsubishi M80 public variable acquisition Mitsubishi CNC variable reading acquisition Mitsubishi CNC remote tool compensation Mitsubishi machine tool online tool
How was my life in 2021
微信公众号网页授权
Katalon框架测试web(二十一)获取元素属性断言
[Yugong series] go teaching course 002 go language environment installation in July 2022
Detailed explanation of PPTC self recovery fuse
Cesiumjs 2022^ source code interpretation [0] - article directory and source code engineering structure
Future源碼一觀-JUC系列
Balance between picture performance of unity mobile game performance optimization spectrum and GPU pressure
Support the first triggered go ticker
Activiti7 task service - process variables (setvariable and setvariablelocal)
Zigzag scan
[paddleseg source code reading] paddleseg calculation dice
Summary of Chinese remainder theorem
Mindmanager2022 efficient and easy to use office mind map MindManager
选择排序与冒泡排序模板
Smart subway | cloud computing injects wisdom into urban subway transportation
ctf-pikachu-CSRF
vim映射命令