Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Why not use isSuccess as the variable name

2025-01-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the knowledge of "Why not use isSuccess as a variable name". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In daily development, we often define Boolean variables in the class. For example, when providing an RPC interface to an external system, we usually define a field to indicate whether the request is successful or not.

As for the definition of the field of "whether this request is successful or not", there are actually many kinds of pits, which will fall into the pit if you are not careful. The author encountered a similar problem a long time ago. This article will briefly analyze this. Exactly how to define a Boolean type member variable.

In general, we can define a Boolean member variable in four ways:

Boolean success

Boolean isSuccess

Boolean success

Boolean isSuccess

Which of the above four definitions are most commonly used in your daily development? Which one is the correct posture?

Through observation, we can find that the main difference between the first two and the latter two is the type of variable, the former using boolean, the latter using Boolean.

In addition, when defining variables, the first and third are named success, while the other two are named using isSuccess.

First of all, let's analyze whether it should be named after success or better with isSuccess.

Success or isSucces?

Should you use success or isSuccess to name the variable? In terms of semantics, both naming methods make sense, and there is no ambiguity. So what other principles can we refer to to let us make a choice?

In Alibaba's Java development manual, there is a "mandatory" provision on this point:

So, why is there such a rule? Let's take a look at the difference between the different names of Boolean variables in POJO.

Class Model1 {

Private Boolean isSuccess

Public void setSuccess (Boolean success) {

IsSuccess = success

}

Public Boolean getSuccess () {

Return isSuccess

}

}

Class Model2 {

Private Boolean success

Public Boolean getSuccess () {

Return success

}

Public void setSuccess (Boolean success) {

This.success = success

}

}

Class Model3 {

Private boolean isSuccess

Public boolean isSuccess () {

Return isSuccess

}

Public void setSuccess (boolean success) {

IsSuccess = success

}

}

Class Model4 {

Private boolean success

Public boolean isSuccess () {

Return success

}

Public void setSuccess (boolean success) {

This.success = success

}

}

The setter/getter of the above code is automatically generated using Intellij IDEA. If you take a closer look at the above code, you will find the following rules:

The getter and setter methods that are automatically generated by the base type have names of the form isXXX () and setXXX ().

The getter and setter methods that are automatically generated by the wrapper type have names of the form getXXX () and setXXX ().

Now that we have agreed to use the basic type boolean to define member variables, let's take a specific look at the difference between Model3 and setter/getter in Model4.

3y: the students here may be a little confused, why it is said here that "there is a consensus to use the basic type boolean to define member variables". In fact, the original author wrote two articles on this article. As for why the original author favors the use of basic data types, you can see why you approve of boolean using basic data types. There is also a corresponding explanation later in this article.

We can find that although the member variables in Model3 and Model4 have different names, one is success and the other is isSuccess, their automatically generated getter and setter method names are both isSuccess and setSuccess.

The specification of setter/getter in Java Bean

In fact, the definition of getter/setter method in JavaBean is clearly defined. According to JavaBeans (TM) Specification, if it is an ordinary parameter and named propertyName, its setter/getter needs to be defined in the following ways:

Public get ()

Public void set (a)

However, the Boolean variable propertyName is a different set of naming principles:

Public boolean is ()

Public void set (boolean m)

By comparing this JavaBeans specification, we find that in Model4, the variable is called isSuccess, and if it is strictly defined by the specification, his getter method should be called isIsSuccess. But many IDE will be born as isSuccess by default.

So what's the problem with this?

Under normal circumstances, there is actually no impact. But there is a special case where there is a problem, and that is when serialization occurs.

The impact of serialization

Refer to serialization and deserialization of Java objects for serialization and deserialization. Let's take the more commonly used JSON serialization as an example to see the differences between the commonly used fastJson, jackson, and Gson:

/ * *

* @ author Hollis

, /

Public class BooleanMainTest {

Public static void main (String [] args) throws IOException {

/ / specify a Model3 type

Model3 model3 = new Model3 ()

Model3.setSuccess (true)

/ / use fastjson (1.2.16) to serialize model3 into a string and output

System.out.println ("Serializable Result With fastjson:" + JSON.toJSONString (model3))

/ / use Gson (2.8.5) to serialize model3 into a string and output

Gson gson = new Gson ()

System.out.println ("Serializable Result With Gson:" + gson.toJson (model3))

/ / use jackson (2.9.7) to serialize model3 into a string and output

ObjectMapper om = new ObjectMapper ()

System.out.println ("Serializable Result With jackson:" + om.writeValueAsString (model3))

}

}

Class Model3 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 getHollis () {

Return "hollischuang"

}

}

In the Model3 of the above code, there is only one member variable, namely isSuccess, three methods, which are isSuccess and setSuccess automatically generated by IDE, and the other is a method that conforms to the getter naming convention added by the author himself.

The above code outputs the result:

Serializable Result With fastjson: {"hollis": "hollischuang", "success": true}

Serializable Result With Gson: {"isSuccess": true}

Serializable Result With jackson: {"success": true, "hollis": "hollischuang"}

In the results of fastjson and jackson, the isSuccess field in the original class is serialized to success, and it also contains the Hollisvalue. In Gson, there is only the isSuccess field.

We can conclude that when fastjson and jackson serialize an object into a json string, they iterate through all the getter methods in the class through reflection to get getHollis and isSuccess, and then according to the JavaBeans rule, he will think that this is the value of the two properties hollis and success. Directly serialize to json:

{"hollis": "hollischuang", "success": true}

But Gson doesn't do that. He iterates through all the properties in the class by reflection and serializes their values to json:

{"isSuccess": true}

As you can see, due to different serialization tools, the strategies used in serialization are different, so the serialization results for the same object of the same class may be different.

The serialization of getHollis mentioned earlier is only to illustrate the difference in serialization strategy between fastjson, jackson and Gson. Let's put him aside for a moment. After we delete him from Model3, we re-execute the above code to get the result:

Serializable Result With fastjson: {"success": true}

Serializable Result WithGson: {"isSuccess": true}

Serializable Result With jackson: {"success": true}

Now that different serialization frameworks get different json content, what happens if I serialize using fastjson and then deserialize using Gson for the same object?

Public class BooleanMainTest {

Public static void main (String [] args) throws IOException {

Model3 model3 = new Model3 ()

Model3.setSuccess (true)

Gson gson = new Gson ()

System.out.println (gson.fromJson (JSON.toJSONString (model3), Model3.class))

}

}

Class Model3 implements Serializable {

Private static final long serialVersionUID = 1836697963736227954L

Private boolean isSuccess

Public boolean isSuccess () {

Return isSuccess

}

Public void setSuccess (boolean success) {

IsSuccess = success

}

@ Override

Public String toString () {

Return new StringJoiner (",", Model3.class.getSimpleName () + "[,"] ")

.add ("isSuccess=" + isSuccess)

.toString ()

}

}

The above code, output the result:

Model3 [isSuccess=false]

This is the exact opposite of what we expected, because the JSON framework scanned all the getter and found an isSuccess method, and then parsed the variable success according to the JavaBeans specification, serializing the model object into a city string with the content {"success": true}.

According to the json string {"success": true}, the Gson framework looks for the success attribute in the Model class through reflection after parsing, but there is only the isSuccess attribute in the Model class, so isSuccess uses the default value false in the object of the deserialized Model class.

However, once the above code occurs in a production environment, this is definitely a fatal problem.

Therefore, as developers, we should try our best to avoid this problem. For POJO designers, there is only one simple thing to do to solve this problem, and that is to change isSuccess to success.

In this way, the success,getter method for the member variables in this class is isSuccess, which is in full compliance with the JavaBeans specification. Regardless of the serialization framework, the execution result is the same. This problem was avoided from the source.

Quote R University's evaluation of this provision in Alibaba's Java development manual.

Therefore, when defining Boolean variables in POJO, do not use the form isSuccess, but directly use success!

Boolean or boolean?

Earlier, we have described how to choose between success and isSuccess, so after eliminating the wrong answer, the alternative is left:

Boolean success

Boolean success

So, should you use Boolean or boolean to give a Boolean variable?

We know that boolean is the basic data type and Boolean is the wrapper type.

So is it better to use a wrapper type or a basic data type when defining a member variable?

Let's look at a simple piece of code.

/ * *

* @ author Hollis

, /

Public class BooleanMainTest {

Public static void main (String [] args) {

Model model1 = new Model ()

System.out.println ("default model:" + model1)

}

}

Class Model {

/ * *

* specify a success member variable of type Boolean

, /

Private Boolean success

/ * *

* specify a failure member variable of type boolean

, /

Private boolean failure

/ * *

* override the toString method, using Java 8's StringJoiner

, /

@ Override

Public String toString () {

Return new StringJoiner (",", Model.class.getSimpleName () + "[,"] ")

.add ("success=" + success)

.add ("failure=" + failure)

.toString ()

}

}

The output of the above code is:

Default model: Model [success=null, failure=false]

As you can see, when we do not set the value of the field of the Model object, a variable of type Boolean sets the default value to null, while a variable of type boolean sets the default value to false.

That is, the default value of the object is null,boolean, and the default value of the basic data type is false.

In Alibaba's Java development manual, there are also some rules on how to select the type of variable in POJO:

It is suggested that we use the type of packaging. What is the reason?

To take an example of deducting fees, let's make a deduction system. When deducting fees, you need to read the value of a rate from an external pricing system. We expect that the return value of this API will include a floating-point rate field. When we get this worth, we use the formula: amount * rate = cost, and the result is deducted.

If there is an exception in the billing system, he may return a default value, which is null if the field is of type Double and 0.0 if the field is of type double.

If the deduction system does not do any special treatment for the return value of the rate, getting the null value for calculation will directly report an error and block the program. If you get 0.0, you may calculate it directly and deduct the fee after obtaining that the interface is 0. This anomaly cannot be perceived.

This way of defining variables using the wrapper type, blocking the program with exceptions, can then be identified as an online problem. If the basic data type is used, the system may not report an error and assume that there is no exception.

That's all for "Why not use isSuccess as the variable name". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report