当前位置:网站首页>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 .
边栏推荐
- MySql实战45讲【全局锁和表锁】
- 左连接,内连接
- 【PyG】理解MessagePassing过程,GCN demo详解
- MySQL practice 45 lecture [row lock]
- MySQL practice 45 [SQL query and update execution process]
- How to limit the size of the dictionary- How to limit the size of a dictionary?
- MySql實戰45講【SQL查詢和更新執行流程】
- [Fuhan 6630 encodes and stores videos, and uses RTSP server and timestamp synchronization to realize VLC viewing videos]
- VS 2019安装及配置opencv
- Model transformation onnx2engine
猜你喜欢

TCP 三次握手和四次挥手机制,TCP为什么要三次握手和四次挥手,TCP 连接建立失败处理机制

I2C subsystem (II): I3C spec

函数栈帧的创建与销毁

3D drawing example

Joking about Domain Driven Design (III) -- Dilemma

The process of connecting MySQL with docker

Force deduction ----- the minimum path cost in the grid

Installation and use of memory leak tool VLD

Add automatic model generation function to hade

Left connection, inner connection
随机推荐
How to return ordered keys after counter counts the quantity
MySql实战45讲【SQL查询和更新执行流程】
Deep learning: multi-layer perceptron and XOR problem (pytoch Implementation)
【富瀚6630编码存录像,用rtsp服务器及时间戳同步实现vlc观看录像】
分布式事务
[Fuhan 6630 encodes and stores videos, and uses RTSP server and timestamp synchronization to realize VLC viewing videos]
Vs 2019 configuration du moteur de génération de tensorrt
VS 2019 配置tensorRT生成engine
MySQL practice 45 [global lock and table lock]
45 lectures on MySQL [index]
labelme标记的文件转换为yolov5格式
3D drawing example
解决高并发下System.currentTimeMillis卡顿
Agile certification (professional scrum Master) simulation exercise-2
Update and return document in mongodb - update and return document in mongodb
Distributed transaction
VS code配置虚拟环境
文件重命名
Reset or clear NET MemoryStream - Reset or Clear . NET MemoryStream
Chart. JS multitooltip tag - chart js multiTooltip labels