当前位置:网站首页>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 .
边栏推荐
- Opengauss database development and debugging tool guide
- PAT乙级“1104 天长地久”DFS优化思路
- 基于Qt的yolov5工程
- QT based tensorrt accelerated yolov5
- Update and return document in mongodb - update and return document in mongodb
- [algebraic structure] group (definition of group | basic properties of group | proof method of group | commutative group)
- Yiwen takes you to know ZigBee
- Joking about Domain Driven Design (III) -- Dilemma
- Process the dataset and use labelencoder to convert all IDs to start from 0
- 你真的懂继电器吗?
猜你喜欢

Add some hard dishes to the interview: how to improve throughput and timeliness in delayed task scenarios!

I2C subsystem (III): I2C driver

C language beginner level - pointer explanation - paoding jieniu chapter
![[Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)](/img/19/815e7cba81f6eb52db5ef0db556dfd.jpg)
[Chongqing Guangdong education] cultural and natural heritage reference materials of China University of Geosciences (Wuhan)

MySql实战45讲【行锁】

Vs 2019 configuration du moteur de génération de tensorrt

Idea format code idea set shortcut key format code

el-tree搜索方法使用

PAT乙级“1104 天长地久”DFS优化思路

I2C 子系统(二):I3C spec
随机推荐
Edit and preview in the back pipe to get the value writing method of the form
MySQL practice 45 [SQL query and update execution process]
函数栈帧的创建与销毁
Joking about Domain Driven Design (III) -- Dilemma
Réglez la hauteur et lancez le système. Currenttimemillis catton
Kubernetes cluster log and efk architecture log scheme
I2C subsystem (II): I3C spec
I2C 子系統(四):I2C debug
I2C subsystem (I): I2C spec
Opengauss database development and debugging tool guide
VS code配置虚拟环境
[algebraic structure] group (definition of group | basic properties of group | proof method of group | commutative group)
I2C 子系统(四):I2C debug
The idea setting code is in UTF-8 idea Properties configuration file Chinese garbled
From C to capable -- use the pointer as a function parameter to find out whether the string is a palindrome character
The difference between componentscan and componentscans
力扣------网格中的最小路径代价
JS finds all the parent nodes or child nodes under a node according to the tree structure
Spark on yarn资源优化思路笔记
Process the dataset and use labelencoder to convert all IDs to start from 0