Reprint--Write high-quality code: 151 Suggestions for improving Java programs (1th: Common methods and guidelines in Java Development ___ recommended 11~15)

Source: Internet
Author: User

Read Catalogue

    • Recommendation 11: Develop a good habit and show the UID of the Declaration
    • Recommendation 12: Avoid assigning values to invariants in constructors with serialized classes
    • Recommendation 13: Avoid complex assignments for final variables
    • Recommendation 14: Use the private method of the serialization class to solve some of the property persistence problems skillfully
    • Suggest 15:break never forget
Back to top recommendation 11: Develop a good habit and show the UID of the Declaration

We write a class that implements the Serializable interface (the serialized flag interface), and Eclipse immediately gives a yellow warning: you need to add a serial Version ID. Why should we increase it? How did he figure that out? What's the use? Here's how to explain the problem.

The serializable class implements the purpose of the interface for persistence, such as network transport or local storage, providing prerequisite support for system distribution and heterogeneous deployment. Without serialization, now we are familiar with remote calls, object databases are impossible to exist, we look at a simple serialization class:

1 Import java.io.Serializable; 2 public class Person implements Serializable {3     private string name; 4  5 public     string GetName () {6         ret Urn name; 7     } 8  9 public     void SetName (String name) {         this.name = name;11     }12 13}

This is a simple javabean that implements the serializable interface, which can be transmitted over the network or stored locally and then read. Here we pass the object as a Java message service (that is, passing an object over the network), the data type defined in the message queue is ObjectMessage, and the producer (Producer) of the message is defined first, and the code is as follows:

1 public class Producer {2 publicly     static void main (string[] args) {3 person         p = new Person (); 4         p.setname ("Mixed The Devil "); 5         //serialization, save to disk 6         Serializationutils.writeobject (p); 7     }8}

This introduces a tool class Serializationutils, which is used to serialize and deserialize a class and store it on a hard disk (analog network transport) with the following code:

 1 Import Java.io.FileInputStream; 2 Import java.io.FileNotFoundException; 3 Import Java.io.FileOutputStream; 4 Import java.io.IOException; 5 Import Java.io.ObjectInputStream; 6 Import Java.io.ObjectOutputStream; 7 Import java.io.Serializable; 8 9 public class Serializationutils {Ten private static String file_name = "C:/obj.bin"; 11//Serialization of public stat IC void WriteObject (Serializable s) {try {objectoutputstream oos = new ObjectOutputStream (New Fi Leoutputstream (file_name)), Oos.writeobject (s), Oos.close (), and the catch (Filenotfoundex         Ception e) {e.printstacktrace (); catch (IOException e) {e.printstacktrace (); 21             }22}23//deserialization of public static Object ReadObject () {Object obj = null;26 try {27 ObjectInputStream input = new ObjectInputStream (new FileInputStream (file_name)); Obj=input.readobje CT (); InpuT.close (); (FileNotFoundException e) {e.printstacktrace ();. catch (IOException e) {e.printstacktrace (); classnotfoundexception} catch (e) {e.printstacktrace (); }37 return obj;38}39}

Through the object serialization process, a block of memory is converted into a data stream that can be transmitted, and then sent over the network to the message consumer (customer), and then deserialized, to generate the experimental object, the code is as follows:

1 public class Customer {2 public     static void Main (string[] args) {3         //Deserializes 4 person         p= (person) Serializationu Tils.readobject (); 5         System.out.println (P.getname ()); 6     }7}

This is a process of deserialization, that is, the process of converting an object's data stream into an instance, and its output is "dyed villain" after it is run. This is too easy, yes, this is a typical demo of serialization and deserialization. But here's a question: What kind of magic happens if the producer of the message and the consumer of the message (person Class) are different? For example: The person class in the message producer adds an age attribute, and the consumer does not increase the attribute. Why didn't it increase? Because this is a distributed deployment application, you do not even know where the application is deployed, especially when sending messages by radio, it is normal to miss one or two subscribers.

In this case, when the serialized and deserialized classes are inconsistent, a inalidclassexception exception is reported when deserializing, because the class version of the serialization and deserialization changes, and the JVM cannot convert the data stream to an instance object. What does the JVM do to determine the version of a class?

A good question, through Serializableuid, is also called the stream identifier (stream Unique Identifier), which is defined by the version of the class, which can show that the declaration can also be implicitly declared. The display declaration format is as follows:

private static final long serialversionuid = 1867341609628930239L;

The implicit declaration is that I do not declare that your compiler helps me build when compiling. Generated by the package name, class name, inheritance, non-private methods and properties, as well as parameters, return values and many other factors calculated, extremely complex, basically calculated this value is unique.

Serialversionuid how the build has been explained, let's look at the role of Serialversionuid. When the JVM is deserialized, it compares the serialversionuid in the data stream with the serialversionuid of the class, and if the same, the class does not change, it can load the data as an instance; if it's not the same, I'm sorry, my JVM is out of work. Throw an anomaly inviladclassexception show you. This is a very good check mechanism, can ensure that an object even in the network or disk "rolled" once, can still do "mud and not dye", the perfect realization of the consistency of the class.

However, sometimes we need a little exception scenario, such as if my class changes little, can the JVM deserialize my previous object back? is to tell the JVM that "my class version has not changed", according to the Serialversionuid that shows the claim, so that the class you write is up-to-date, and we modify the person class to add the private static final long Serialversionuid = 1867341609628930239L;

At first the producer and consumer hold the person class consistent, is V1.0, one day the producer's person class changed, added an "age" attribute, Upgrade to V2.0, for various reasons (such as programmer negligence, upgrade time window, etc.) the consumer's Person class or V1.0 version, the code is PRIAVTE int age, and the corresponding setter and getter method.

At this point, although the production of this and the corresponding class version of the consumer, but the display declaration of the same serialversionuid, serialization can also be run, the business problem is that the consumer can not read the new business attributes (age attribute). With this example, our deserialization also implements version-up compatibility, which accesses a V2.0 object using the V1.0 version of the application, which undoubtedly improves the robustness of the code. We add a serialversionuid field when we write the serialized class code, and it does not bring much effort, but it can play an extraordinary role at a critical time.

  Display declaration Serialversionuid can avoid inconsistent objects, but try not to lie to the JVM in this way.

Back to top recommendation 12: Avoid assigning values to invariants in constructors with serialized classes

We know that a property with a final identity is a non-variable, that is, it can only be assigned once and cannot be repeated, but it is a bit more complex in a serialization class, such as this class:

1 public class Person implements Serializable {2     private static final long Serialversionuid = 1867341609628930239l;3
   public final String pername= "Cheng Bite Gold"; 4}

The Peson class (at this time the V1.0 version) is serialized and stored on disk, and Pername property recalculates its value when deserializing (unlike the static variable, the static variable is not saved to the data stream at all) such as the Pername property is modified to "Qinshubao" ( Version to V2.0), the deserialized Pername value is "Qinshubao". Keeping the final variables of the old and new objects the same, which facilitates the unification of the Code business logic, is one of the basic principles of serialization, that is, if the final attribute is a direct amount, it is recalculated when deserialized. For the basic principles, let's talk about another way to assign a final variable: Assign a value through a constructor. The code is as follows:

public class Person implements Serializable {    private static final long serialversionuid = 1867341609628930239L;    Public final String Pername;    Public person () {        pername = "path Bite gold";    }}

This is also a commonly used method of assignment, you can define the person class as version V1.0, and then serialize it to see what's wrong with the serialization code as follows:

public class Serialize {public    static void Main (string[] args) {        //serialization to persist        Serializationutils.writeobject (New Person ());}    }

Person's internship object is saved to disk, it is an anemic object (hosting business attribute definition, but does not include its behavior definition), we do a simple simulation, modify the Pername value represents the change, to note that the serialversionuid unchanged, the modified code is as follows:

public class Person implements Serializable {    private static final long serialversionuid = 1867341609628930239L;    Public final String Pername;    Public person () {        pername = "Qinshubao";    }}

At this time the version of the person class V2.0 but serialversionuid unchanged, can still be deserialized, the code is as follows:

public class Deserialize {public    static void Main (string[] args) {person        P = (person) serializationutils.readobj ECT ();        System.out.println (P.pername);    }}

Now the problem comes out, print out the result is "Cheng Bite gold" or "Qinshubao"? The answer is: "Cheng Bite gold". The final type of the variable is not recalculated, it should be printed Qinshubao. Why is it a golden bite? This is because it touches the 21 principles of deserialization: The constructor does not execute when deserializing.

The process of deserialization is this: The JVM obtains an object from the data stream and then describes the information according to the class file in the data flow (when serializing, the object file that is saved to disk contains the class description information, note that the description information, not the Class) is viewed, found to be a final variable, and needs to be recalculated , then refers to the Pername value in the person class, and at this time the JVM found that Pername has no assignment, can not be referenced, so it is very clever no longer initialized, maintain the original value state, so the result is "Cheng Bite gold".

 Note: The constructor is not used in the serialization class to assign a value to the final variable.

Back to top tip 13: Avoid complex assignments for final variables

There is another way to assign a value to the final variable: by assigning a value by method, by assigning a value directly at the time of the declaration by the method's return value, or by taking the person class as an example, the code is as follows:

public class Person implements Serializable {    private static final long serialversionuid = 1867341609628930239L;    The final variable is assigned a public    final String pName = Initname () by means of the method return value;    Public String Initname () {        return "path Bite gold";    }}

The PName property is assigned by the return value of the Initname method, which is often used in complex classes, which is simpler and easier to modify than using a constructor, so will this use be problematic when serializing? Let's see it together. The Person class is written (defined as V1.0 version), it is serialized, stored in the local file, the code is the same as before, not repeat. Now the code for the person class needs to be modified, and the return value of Initname is changed to "Qinshubao". So what would the pname be like when the instance we stored on disk was loaded?

Now, the code for the person class needs to be modified, and the return value of Initname has changed, as follows:

public class Person implements Serializable {    private static final long serialversionuid = 1867341609628930239L;    The final variable is assigned a public    final String pName = Initname () by means of the method return value;    Public String Initname () {        return ' Qinshubao ';    }}

The previous code only modifies the return value of Initname (the person class is the V2.0 version) that is, the value of the final variable of the object generated by new is "Qinshubao", then we load the instance that was previously stored on disk, what is the value of pname?

The result is "Cheng Bite gold", very surprised, last suggested that the final variable will be re-assigned value, but this example is not re-assigned, why?

The last suggested re-assignment, where "value" refers to a simple object. Simple objects include: 8 basic types, as well as arrays, strings (strings are complicated, string objects that are not generated by the New keyword are assigned the same as the base type), but cannot be assigned a value.

The principle is that the object file saved to disk (or network transport) consists of two parts:

(1). Class description information: Includes classpath, inheritance relationships, access permissions, variable descriptions, variable access permissions, method signatures, return values, and association class information for variables. One thing to note is that it is not a copy of the class file, it does not record specific implementations of methods, constructors, static variables, and so on. The reason the class description will be saved is simple, because it is possible to go back, which guarantees the robust operation of deserialization.

(2). Non-transient (transient keywords) and non-static (static keyword) entity variable values

Note that the value here if it is a basic type, say, is a simple value to save, if it is a complex object, it is also simple, even the object and the associated class information is saved, and continue to recursively (the association class must also implement the Serializable interface, otherwise there will be a serialization exception), That is, recursion to the end, or the preservation of the basic data type.

Because of these two reasons, a persistent object file is much larger than a class file, and interested readers can test it themselves, and the volume does swell a lot.

 To summarize: When deserializing, the final variable is not re-assigned in the following cases:

    1. Assigning a value to a final variable through a constructor
    2. Assign a value to the final variable by a method return value
    3. Final decorated properties are not basic types
Back to top recommendation 14: Use the private method of the serialization class to skillfully resolve partial property persistence problems

The partial attribute persistence problem may seem simple, as long as the properties that do not need to be persisted are added to the transient keyword (transient keyword). This is a solution, but sometimes it doesn't work. For example, a tax system and an HR system, through the RMI (remote method invocation, long-distance methods call) docking, the tax system needs to obtain personnel's name and basic salary from the HR system, as the basis of tax payment, And the HR system's wages are divided into two parts: basic salary and performance pay, basic salary is not secret, performance pay is confidential, can not be disclosed to the outside system, which is clearly connected with a class, first look at the salary class salary code:

1 public class Salary implements Serializable {2     private static final long serialversionuid = 2706085398747859680L; 3     //Base salary 4     private int basepay; 5     //performance pay 6     private int bonus; 7 8 public     Salary (int _basepay, int _bonus) {9         this.basepay = _basepay;10         this.bonus = _bonus;11     }12//setter and getter method slightly 13 14}

The person class and the salary class are association relationships with the following code:

1 public class Person implements Serializable {2  3     private static final long Serialversionuid = 914617688014302 6279L; 4  5     private string name; 6  7     private Salary Salary; 8  9 Public person     (String _name, Salary _salary) {         this.name = _name;11         this.salary = _salary;12     }13//setter     and getter method slightly 15 16}

This is a two simple javabean, all implemented the serializable interface, with the conditions of serialization. First, the tax system requests the HR system to serialize a person object, transferring personnel information and payroll information to the tax system, with the following code:

1 public class Serialize {2 public     static void Main (string[] args) {3         //base salary 1000 yuan, performance wage 2500 Yuan 4         Salary Salary = new Salary (1000, 2500); 5         //Record personnel information 6 person people         = new Persons ("Zhang San", salary), 7         //hr system persistence, and delivery to the tax system 8         Serializationutils.writeobject (person); 9     }10}

After transmission over the network to the tax system, the following code is deserialized:

1 public class Deserialize {2 publicly     static void main (string[] args) {3 person         p = (person) SERIALIZATIONUTILS.R Eadobject (); 4         StringBuffer buf = new StringBuffer (); 5         buf.append ("Name:" +p.getname ()); 6         buf.append ("\ t base salary:" +p.getsalary (). Getbasepay ()); 7         buf.append ("\ t performance pay:" +p.getsalary (). Getbonus ()); 8         System.out.println (BUF); 9     }10}

The printed result is: Name: Zhang San base salary: 1000 Performance Salary: 2500

However, this does not meet the demand, because the tax system only from the HR system to obtain the person's name and basic salary, and performance pay is not available, this is a confidential data, not allowed to leak. How to solve this problem? You might think of the following four scenarios:

    1. Add keyword transient before bonus: This is a method, but not a good method, plus transient keyword will mark salary lost the function of distributed deployment, it may be the core class of HR system, once encountering performance bottleneck, it is possible to implement distributed deployment , this scheme is negative;
    2. New business object: Add a Person4tax class, fully service the tax system, that is, it only has two attributes: Name and base salary. In line with the principle of open and closed, but also to the original system is not invasive, only increased the workload. But this method is not the optimal method;
    3. Request-side filtering: After acquiring the person object in the tax system, filtering out the bonus attribute of the salary, the scheme is feasible but does not conform to the rules, because the salary class security in the HR system is unexpectedly out of the system (tax system to assume), the design of serious negligence;
    4. Change the transfer contract: for example, instead of using an XML transport, or rebuilding a webserive service, it can be done but at a high cost.

The following shows an excellent scenario where a class that implements the serializable interface can implement two private methods: WriteObject and ReadObject, to influence and control the process of serialization and deserialization. Let's change the person class to see how to control serialization and deserialization, with the following code:

1 public class Person implements Serializable {2  3     private static final long Serialversionuid = 91461768801430262 79L; 4  5     private string name; 6  7     private transient Salary Salary; 8  9 Public person     (String _name, Salary _salary) {         this.name = _name;11         this.salary = _salary;12     }13     //Serialization delegate method +     private void WriteObject (ObjectOutputStream oos) throws IOException {         oos.defaultwriteobject ();         Oos.writeint ( Salary.getbasepay ());     }18     //Deserialization delegate method,     private void ReadObject (ObjectInputStream input) throws ClassNotFoundException, IOException {         input.defaultreadobject ();         salary = new Salary (Input.readint (), 0);     }23}

Other code does not make any changes, after running the result is: Name: Zhang San base salary: 1000 Performance Salary: 0

The WriteObject and ReadObject two methods are added to the person class, and access permissions are private, so why do you change the results of the program? In fact, there is a unique mechanism for serialization: serialization callbacks. When Java calls the ObjectOutputStream class to convert an object into a data stream, it checks to see if the serialized class has a WriteObject method through reflection (Refection), and checks whether it conforms to the property of private, no return value, if any, The method is delegated for object serialization, and if not, the ObjectOutputStream continues to serialize according to the default rules. Similarly, when recovering from streaming data to an instance object, it also checks for a private ReadObject method that, if any, reads the value of the property, and here are a few key points to note:

    1. Oos.defaultwriteobject (): Tells the JVM to write to the object according to the default rules, which are written in the first line.
    2. Input.defaultreadobject (): tells the JVM to read the object in accordance with the default rules, which are written in the first line.
    3. Oos.writexx and Input.readxx

The corresponding values are written and read out, similar to a queue, FIFO, if there is complex data logic, it is recommended to package collection object processing. You may notice that the above method is also the person lost the ability of distributed deployment, indeed, but the difficulty and focus of the HR system is the salary calculation, especially the performance pay, it depends on the parameters are very complex (only in terms of the number of hundreds or even thousands of), the calculation formula is not simple (usually introduced in scripting language, Personalized formula customization) whereas the person class is basically a static property, the probability of a calculation is small, so even for performance reasons, the person class is not very meaningful for distributed deployments.

Back to top advice 15:break never forget

We often write some conversion classes, such as currency conversion, date conversion, transcoding, etc., in the financial field to use the largest number of Chinese digital conversion, such as the "1" into "one", but open source tools will not provide this tool class, because it is too close to Chinese culture, it needs to write:

1 public class Client15 {2 public     static void Main (string[] args) {3         System.out.println (tochinesenubercase (0)); 4     } 5  6 public     static string tochinesenubercase (int n) {7         string chinesenumber = ""; 8         switch (n) {9 case         0:10             chinesenumber = "0"; one case         1:12             chinesenumber = "one"; case         2:14< C12/>chinesenumber = "II"; case         3:16             chinesenumber = "three";         4:18             chinesenumber = "Restaurant"; 19 Case         5:20             chinesenumber = "WU"; case         6:22             chinesenumber = "Lu"; case         7:24             Chinesenumber = "Qi";         8:26             chinesenumber = "ba"; case         9:28             chinesenumber = "JIU";         }30< C28/>return chinesenumber;31     }32}

This is a simple code, but the result is "nine", this is very simple, may be in the first contact with the grammar has been learned, but simple, if the programmer omitted to write, simple problems will cause great consequences, and even economic losses. So use the switch statement to remember to add break, to form a good habit. For this kind of problem, in addition to the usual caution, you can use unit testing to avoid, but we all know that when the project is tight, may but the unit test is not covered. So one of the simplest ways to do this is to modify the IDE's warning level, for example, in Eclipse, you can click Performaces-->java-->compiler-->errors/warings--> Potential programming problems, then modify the ' switch ' case fall-through to errors level, if you dare not to add a break in the box statement, Eclipse will report a red fork to you, This will prevent the problem from happening. But it is more important to develop good habits.

Reprint--Write high-quality code: 151 Suggestions for improving Java programs (1th: Common methods and guidelines in Java Development ___ recommended 11~15)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.