当前位置:网站首页>New programmers use the isXXX form to define Boolean types in the morning, and are discouraged in the afternoon?
New programmers use the isXXX form to define Boolean types in the morning, and are discouraged in the afternoon?
2022-07-03 03:12:00 【Friendship years】
The waiter is the new pot bearer , Oh , No no no , The new intern . I did very well in the interview , All kinds of questions were answered fluently , The boss and I are very happy .
Such an excellent person , Never let him waste a minute , So soon , I arranged a very simple task for him .
Everybody knows , In daily development , We often have to define Boolean variables in a class , For example, it is providing an external system with RPC At the interface , We usually define a field to indicate whether the request was successful .
About this ” Whether this request is successful ” The definition of the field of , I've seen a lot of different developers , They are defined in different ways , Especially in the naming of attributes , Someone uses it success, Someone uses it isSuccess Express .
Semantically speaking , Both naming methods make sense , And there's no ambiguity .
see , The waiter adopted isSuccess To define variables of boolean type , So in the afternoon review I was picked out by the boss with sharp eyes . After all, the boss was in Ali , Buckle these details very carefully .
So I was furious , Prepare to dissuade the waiter on the spot , I stopped it . After all, the person you interview , Don't look at the Buddha's face , Is that so? ? So the boss promised me to try it for another month .
isSuccess What's the problem ? The waiter was puzzled .
That's the basis JavaBeans Specification The provisions of the , If it's a normal parameter propertyName, Define it in the following way setter/getter:
public <PropertyType> get<PropertyName>();
public void set<PropertyName>(<PropertyType> a);
however , Boolean variables propertyName It is defined separately :
public boolean is<PropertyName>();
public void set<PropertyName>(boolean m);
success Methodical getter Should be isSuccess/getSuccess, and isSuccess Of getter Should be isIsSuccess/getIsSuccess.
But a lot of people , In the use of isSuccess As an attribute name , Still use isSuccess/getSuccess As getter Method name , Especially now many IDE Generate by default getter It will also generate isSuccess.
In general , In fact, it has no effect . But there's a special case where there's a problem , That is, serialization may cause parameter conversion exceptions .
Let's define a JavaBean:
class Model implements Serializable {
private static final long serialVersionUID = 1836697963736227954L;
private boolean isSuccess;
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean success) {
isSuccess = success;
}
public String getWanger(){
return "hollis";
}
}
In this JavaBean in , There is a member variable isSuccess, Three methods , Namely IDE Automatically generated for us isSuccess and setSuccess, The other is the author's own addition of a consistent with getter The method of naming conventions .
We use different JSON Serialize and deserialize the objects of this class with a sequencer :
public class BooleanMainTest {
public static void main(String[] args) throws IOException {
// Order one Model type
Model model = new Model();
model.setSuccess(true);
// Use fastjson(1.2.16) serialize model Form a string and output
System.out.println("Serializable Result With fastjson :" + JSON.toJSONString(model));
// Use Gson(2.8.5) serialize model Form a string and output
Gson gson =new Gson();
System.out.println("Serializable Result With Gson :" +gson.toJson(model));
// Use jackson(2.9.7) serialize model Form a string and output
ObjectMapper om = new ObjectMapper();
System.out.println("Serializable Result With jackson :" +om.writeValueAsString(model));
}
}
The output of the above code :
Serializable Result With fastjson :{"wanger":"hollis","success":true}
Serializable Result With Gson :{"isSuccess":true}
Serializable Result With jackson :{"success":true,"wanger":"hollis"}
stay fastjson and jackson The results of , In the original class isSuccess Fields are sequenced into success, And it also includes wanger value . and Gson There are only isSuccess Field .
We can come to a conclusion :fastjson and jackson Is serializing objects into json String time , It's going to traverse all of this class by reflection getter Method , obtain getHollis and isSuccess, And then according to JavaBeans The rules , He would think that these are two attributes hollis and success Value . Directly sequenced into json:
{“wanger”:” Silent king two ”,”success”:true}however Gson It's not that , He traverses all the attributes in this class through reflection , And sequence the values into json:
{“isSuccess”:true}
You can see , Due to different serialization tools , The strategy used in serialization is different , therefore , The serialization result of the same object of the same class may be different . that , If we use an object fastjson serialize , Reuse Gson What happens to deserialization ?
public class BooleanMainTest {
public static void main(String[] args) throws IOException {
Model model = new Model();
model.setSuccess(true);
Gson gson =new Gson();
System.out.println(gson.fromJson(JSON.toJSONString(model),Model.class));
}
}
Above code , Output results :
Model[isSuccess=false]
This is exactly the opposite of what we expected , The reason is because JSON The framework scans all the getter I found out that there was one isSuccess Method , And then according to JavaBeans The specification of , The variable name is resolved as success, hold model After the object is serialized into a string, the content is {"success":true}.
according to {"success":true} This json strand ,Gson After the framework is parsed , Looking for by reflection Model Class success attribute , however Model Class only isSuccess attribute , therefore , After the final deserialization Model Class ,isSuccess The default value will be used false.
however , Once the above code occurs in the production environment , This is absolutely a fatal problem .
therefore , As a developer , We should try our best to avoid this kind of problem .
therefore , We suggest you use success instead of isSuccess This form . such , When the member variable in this class success,getter The method is isSuccess, This is exactly in line with JavaBeans canonical . No matter what serialization framework , The results are the same . This problem is avoided from the source .
边栏推荐
- What happens between entering the URL and displaying the page?
- JS finds all the parent nodes or child nodes under a node according to the tree structure
- Idea format code idea set shortcut key format code
- 从输入URL到页面展示这中间发生了什么?
- BigVision代码
- labelme标记的文件转换为yolov5格式
- MySql实战45讲【行锁】
- 从C到Capable-----利用指针作为函数参数求字符串是否为回文字符
- Do you really understand relays?
- C语言初阶-指针详解-庖丁解牛篇
猜你喜欢
![MySQL practice 45 [SQL query and update execution process]](/img/cd/3a635f0c3bb4ac3c8241cb77285cc8.png)
MySQL practice 45 [SQL query and update execution process]

I2C subsystem (II): I3C spec

Idea format code idea set shortcut key format code

Pytest (6) -fixture (Firmware)

Kubernetes cluster log and efk architecture log scheme

Can netstat still play like this?
![ASP. Net core 6 framework unveiling example demonstration [02]: application development based on routing, MVC and grpc](/img/cb/145937a27ef08050a370d5a255215a.jpg)
ASP. Net core 6 framework unveiling example demonstration [02]: application development based on routing, MVC and grpc

The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled

Vs Code configure virtual environment

【PyG】理解MessagePassing过程,GCN demo详解
随机推荐
Pytorch配置
PAT乙级“1104 天长地久”DFS优化思路
C#通用接口调用
PAT乙级常用函数用法总结
yii2 中andWhere多个or查询 orm条件
将时间戳转为指定格式的时间
I2C subsystem (II): I3C spec
[Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)
Segmentation fault occurs during VFORK execution
从C到Capable-----利用指针作为函数参数求字符串是否为回文字符
Kubernetes cluster log and efk architecture log scheme
[leectode 2022.2.15] lucky numbers in the matrix
敏捷认证(Professional Scrum Master)模拟练习题-2
Add some hard dishes to the interview: how to improve throughput and timeliness in delayed task scenarios!
JS finds all the parent nodes or child nodes under a node according to the tree structure
45 lectures on MySQL [index]
Idea set method call ignore case
ComponentScan和ComponentScans的区别
模型转换onnx2engine
Notifydatasetchanged not applicable to recyclerview - notifydatasetchanged not working on recyclerview