Reprint-write high-quality Code: 151 suggestions for improving Java programs (3rd: classes, objects and methods ___ recommended 41~46)

Source: Internet
Author: User
Tags serialization shallow copy

Read Catalogue

    • Recommendation 41: make multiple inheritance a reality
    • Recommendation 42: make a tool class non-instantiated
    • Recommendation 43: Avoid shallow copies of objects
    • Recommendation 44: The use of a copy of a serialized object is recommended
    • Recommendation 45: do not identify yourself when you overwrite the Equals method
    • Suggested 46:equals should consider a null value scenario
Back to top tip 41: make multiple inheritance a reality

In java, a class can be implemented in multiple implementations, but not multiple inheritance, meaning that a class can implement multiple interfaces at the same time, but cannot inherit multiple classes at the same time. But sometimes we do need to inherit multiple classes, such as the ability to have multiple classes of behavior, it is difficult to use single inheritance to solve the problem (of course, using multiple inheritance can be solved). fortunately, the inner classes provided in Java can solve this problem in a tortuous way, so let's take a look at a case that defines a father and mother interface that describes the ideal situation where the father is strong, the mother is gentle, and the code is as Follows:

public interface Father {public    int strong ();} Interface Mother {public    int Kind ();}

The return values of strong and kind represent strong and gentle indices, the higher the index, the higher the strength and tenderness, the same as the character set in the game, and we continue to look at the two implementations of father and Mother:

Class Fatherimpl implements Father {    //father's Strong index is 8    @Override public    int strong () {        return 8;    }} Class Motherimpl implements Mother {    //mother's Gentleness index is 8    @Override public    int Kind () {        return 8;    }}

The father's strong index is 8, the Mother's gentleness index is also 8, good match, then their sons and daughters must be better, we look at the son class, the code is as Follows:

Class son extends Fatherimpl implements mother {    @Override public    int strong () {        //son stronger than Father        return su Per.strong () + 1;    }    @Override public    int Kind () {        return new motherspecial (). kind ();    }    Private class Motherspecial extends Motherimpl {        @Override public        int kind () {            //son's Gentle index lowers            return Super.kind ()-1;}}    }

The son inherits from his father, becomes stronger than his father (strong method), while the son also has the advantage of the mother, but the gentle index is Reduced. Notice that this constructs the Motherspecial class to inherit the mother class, that is, to obtain the mother class behavior and methods, which is also an important feature of the inner class: the inner class can inherit a class independent from the external class, to ensure the independence of the inner class, It is based on this point, multiple inheritance will be possible. This inner class of motherspecial is called the member inner class (also called the instance inner class, Instance Inner class), Let's look at the daughter class, the code is as Follows:

Class daughter extends Motherimpl implements Father {    @Override public    int strong () {        return new Fatherimpl () {            @Override public            int strong () {                //daughter's Strong index decreased by                return Super.strong ()-2;}        }. Strong ();    }}

The daughter inherited the current tenderness index, while also covering the father's strong index, not much Explanation. Note the strong method of overwrite, here is the creation of an anonymous inner class (Anonymous Inner Class) to override the parent class method to complete the function of inheriting the father's Behavior.

Multiple inheritance refers to a class can inherit the behavior and characteristics from many and one father at the same time, according to this definition, our son class, the daughter class has realized from the father and the mother to inherit all functions, should belong to the multi-inheritance, this is entirely attributed to the internal class, we need to use multiple inheritance, You can think about the inner class.

In real life, There is also a problem of multiple inheritance, the above example says descendants inherit the father also inherited the mother's behavior and characteristics, such as China's Special animal "sibuxiang" (scientific name elk), its shape "like deer non-deer, like horse non-horse, like cattle non-cattle, like donkey non-donkey", which you want to use a single inheritance is more troublesome If you use multiple inheritance, you can solve this problem well: define deer, horse, ox, donkey four classes, and then build the Elk class of multiple internal classes, inherit Them.

Back to top recommendation 42: make a tool class non-instantiated

Java projects use a lot of tools, such as the Jdk's own tool class java.lang.Math, java.util.Collections, etc. are often used by us. Tool class methods and properties are static, do not need to generate an instance to access, and the JDK has done a good job, because do not want to be initialized, so set the constructor private access, indicating that the class itself, no one can produce an instance, we Take a look at the Java.lang.Math code:

Public final class Math {    /**     * Don ' t let anyone instantiate this class.     *    /private Math () {}}

The reason for the "don't let anyone instantiate this class." is to stay because the constructor for math is set to private: I'm A tool class, I just want other classes to be accessed through the class name, and I don't want you to access it through the instance Object. This is sufficient in a platform or framework Project. But if you have been told not to do so, you also want to generate a Math object instance to access static methods and properties (java reflection is so developed, modify the access rights of a constructor is a breeze), then I do not guarantee correctness, hidden problems can erupt at any time! So do we have a better way of restricting the project? there, that is not only set to private permissions, but also throws an exception, the code is as Follows:

Class Utilsclazz{public    Utilsclazz () {        throw new Error ("Don t instantiate" +getclass ())}    }

This ensures that a tool class is not instantiated and that all accesses are made through the class Name. It is important to note that this tool class is not intended to be integrated, because if a subclass can be instantiated, the constructor of the parent class is called, but the parent does not have a constructor that can be accessed, and the problem Arises.

Note: if a class does not allow instantiation, ensure that the "normal" channel cannot instantiate it.

Back to top tip 43: avoid shallow copies of objects

We know that a class that implements the Cloneable interface means that it has the ability to be copied. If you overwrite the clone () method, you will have full copy Capability. The copy is run in memory, so it is much faster in terms of performance than the object directly generated by new, especially on large object generation, which makes performance improvements very noticeable. But the object copy also has a relatively easy to ignore problem: shallow copy (Shadow Clone, also known as Shadow Copy) has the problem that the object property copy is not Complete. Let's look at this piece of code:

 1 public class man implements cloneable {2 public static void main (string[] Args) {3//definition father 4 P Erson f = new person ("father"); 5//define the older son 6 person s1 = new person ("big son", f); 7//the youngest Son's message was copied over by the older sons of 8 person s2 = S1.clone (); 9 s2.setname ("youngest"), System.out.println (s1.getname () + "father is" + s1.getfather (). getName ());     Ystem.out.println (s2.getname () + "father is" + s2.getfather (). getName ()); 12}13//name + private String name;15 Father-private person father;17 (String _name) {publi name = _name;20}21     C person (String _name, person _parent) {_name;24 = father = _parent;25}26 @Override28         Public person clone () {p = null;30 try {p = (person) Super.clone (); 32 } catch (clonenotsupportedexception E) {e.printstacktrace ();}35 return p;36 37}38/*setter and getter method slightly */40} 

In the program we describe a scenario in which a father, with two sons, is of the same size as the son, so the youngest Son's object is generated by copying the object of the big boy, and the output of the run is as Follows:

    The father of the older son is the father
The youngest Son's father is the Father.

  That's right, No Problem. Suddenly one day, father whim want to let the big son to recognize a godfather, that is, the father of the big son name needs to be reset, the code is as Follows:

    public static void main (string[] Args) {        //define father person        f = new person ("father");        Define the big son person        s1 = new person ("big son", f);        The youngest Son's message was copied over by the big boy        s2 = s1.clone ();        S2.setname ("youngest son");        s1.getfather (). setName ("godfather");        System.out.println (s1.getname () + "father is" + s1.getfather (). getName ());        System.out.println (s2.getname () + "father is" + s2.getfather (). getName ());    }

The older son re-set the father's name, we expect the output is: the father of the older son to change the name of the father-in-the-godfather, the youngest Son's dad name remains Unchanged. Run the results as Follows:

The father of the older son is the Godfather.
The youngest Son's father is a godfather.

  What is the matter, the youngest Son's father has become the "godfather"? Two sons all wood has, This Lao Tze estimate is to be angry to die! The reason for this problem is that the clone method, we know that all classes inherit from Object,object provides an object copy of the default method, that is, the page code in the Super.clone () method, But the method is flawed, he provides a shallow copy, This means that it does not copy all of the properties of the object, but a copy of the selection, with the following copy rules :

    1. Base type: If the variable is a base type, copy its Value. such as int, float, etc.
    2. Object: If the variable is an instance object, copy its address reference, which means that the copied object shares the instance variable with the original object and is not controlled by Access rights, which is crazy in Java because it breaks through the definition of access: a private modified variable, can be accessed by two different instance objects, which makes Java's access rights System.
    3. String String: This is special, the copy is an address, is a reference, but when modified, it will regenerate a new string from the string pool, the original string object remains unchanged, where we can think of a string is a basic type.

Understanding these three principles, the above example is very clear. The youngest Son's object was a copy of the big boy, whose father was the same person, that is, the same object, the older son changed his father's name, the youngest son was also very modified-so the father's two sons are Gone. In fact, to correct is also very simple, the code of the Clone method is as Follows:

Public person clone () {person        p = null;        Try {            p = (person) Super.clone ();            P.setfather (new person (p.getfather (). getName ()));        } Catch (clonenotsupportedexception e) {            e.printstacktrace ();        }        return p;    }

And then run, the younger Son's father will not be the godfather, so that the deep copy of the object to achieve the self-contained, to ensure that the copy of the object is not affected by the "mother", and the object of the new generation is no Different.

 Note: shallow copy is just a simple copy mechanism provided by Java and is not easy to use directly.

Back to top recommendation 44: use a copy of the serialized object is recommended

The previous suggestion that the Object's shallow copy problem, The test Cloneable interface has the ability to copy, then we think about the question: if a project has a large number of objects are generated through the copy, then we how to deal with it? Each class is tied to a clone method and has a deep copy? Think about what a huge workload it is! Is there a better way to do it?

In fact, can be processed by serialization, in memory through the byte stream copy to achieve, that is, the mother object written into a byte stream, and then read it out of the byte stream, so that you can reconstruct an object, the new object and the parent object does not have a reference sharing problem, it is equivalent to a deep copy of an object, The code is as Follows:

 1 Import java.io.ByteArrayInputStream; 2 Import java.io.ByteArrayOutputStream; 3 Import java.io.IOException; 4 Import java.io.ObjectInputStream; 5 Import java.io.ObjectOutputStream; 6 Import java.io.Serializable; 7 8 Public final class Cloneutils {9 private cloneutils () {ten throw new Error (cloneutils.class + "cannot in Stance "); 11}12 13//copy an object in public static <t extends serializable> T clone (T Obj) {15//copy production  Raw Object cloneobj = null;17 Try {18//read object byte data bytearrayoutputstream BAOs = new Bytearrayoutputstream (); ObjectOutputStream oos = new ObjectOutputStream (baos); oos.writeobje CT (cloneobj); oos.close (); 23//allocate Memory space, write to original object, generate new object Bytearrayinputstream Bais = NE             W bytearrayinputstream (baos.tobytearray ()); objectinputstream ois = new ObjectInputStream (bais); 26 Return the new object and do type conversion cloneobj = (T) OIS.REadobject (); ois.close (); catch (classnotfoundexception e) {e.printstacktrace (); 3  1} catch (ioexception e) {e.printstacktrace ();}34 return cloneobj;35 36}37 38}

This tool class requires the copied object to implement the serializable interface, otherwise there is no way to copy (of course, using reflection is another technique), the previous example is only slightly modified to achieve a deep copy, the code is as follows

public class person implements serializable{    private static final long Serialversionuid = 4989174799049521302L;        /* Remove clone method, other code remains the same */}

The copied class as long as the implementation of serializable this iconic interface can be, do not need any implementation, of course, Serialversionuid constant is to add, and then we can use the Cloneutils tool to carry out the deep copy of the object, There are two points to note when using the Word method for object copying:

    1. The intrinsic properties of an object are serializable: if there are internal properties that are not serializable, a serialization exception is thrown, which makes the debugger wonder how a serialized exception can be generated when an object is Built. From this point of view, it is also necessary to refine the cloneutils Tool's Exception.
    2. Note the special modifiers for methods and Properties: for example, the serialization of a final,static variable is introduced into the Object's copy, which requires special attention, while the transient variable (transient variable, non-serialized Variable) also affects the copy Effect. Of course, there is an easier way of using serialized copies, which is to use the Serializationutils class in the Commons Toolkit under apache, which is straightforward to Use.
Back to top tip 45: do not identify yourself when you overwrite the Equals method

When we write a javabean, we often overwrite the equals method, which is designed to determine whether two objects are equal according to business rules, such as when we write a person class and then determine whether two instance objects are the same by name, which in DAO (Data Access Objects) layers are often used. When you do this, get two dtos (data Transfer object, data transfer objects) from the database, and then determine if they are equal, and the code is as Follows:

public class person {    private String name;    Public person (String _name) {        name = _name;    }    Public String getName () {        return name;    }    public void SetName (String name) {        this.name = name;    }        @Override public    boolean equals (Object obj) {        if (obj instanceof person) {person            p = (person) obj;            return name.equalsignorecase (p.getname (). trim ());        return false;    }}

Overwrite the Equals method to do a number of checks, considering that the Web upload passed the object may have entered before and after the space, so cut with the trim method, to see if the code is not a problem, we write a main:

public static void main (string[] Args) {person        p1= new person ("zhang san");        Person p2= the new person ("zhang San  ");        list<person> list= new arraylist<person> ();        List.add (p1);        List.add (p2);        System.out.println ("the list contains Zhang san:" +list.contains (p1));            System.out.println ("the list contains Zhang san:" +list.contains (p2));    }

The above code produces two person objects (note that the Zhang San in the P2 variable has a space behind it), and then it is placed in the list and finally determines whether the list contains the two Objects. Look no problem, you should print out two true, but the result is:

Whether the list contains Zhang San: true
Whether the list contains Zhang San: false 

The object just put in the list said no, this is disappointing, why? The list class checks whether the containing element is always judged by invoking the Equals method of the object, that is, contains (p2) is passed in, executes p2.equals (p1) sequentially, p2.equals (p2), and only one returns true, and the result is True. unfortunately, The comparison is false, and the problem comes out:

P2.equals (p2) because false?

That's true, p2.equals (p2) is really false, look at our equals method, it cuts the second parameter! In other words, the following equation is Compared:

"zhang San  ". equalsignorecase ("zhang san");

Note that the front of the Zhang san, there is a space, the result is definitely false, the error also arose, this is a good thing but to do a "bad" case, it violates the Equlas method of the reflexive principle: for any non-null reference x,x.equals (x) Should return true, the problem until the resolution is very simple, just remove trim (). Note that only the current problem is resolved, and there are other issues with the equals method.

Back to top recommended 46:equals should consider a null value scenario

Continuing with the 45 suggested questions, we solved the question of the reflexive nature of the overwrite equals, is it perfect? To refactor the main method:

public static void main (string[] Args) {person        p1= new person ("zhang san");        Person p2= the new person (null);
/* no changes in other parts, no more repeating */}

Very small changes, you must know that the result is the package "null pointer" Exception. The reason is also very simple: the Null.equalsignorecase method naturally error, here is to illustrate the principle of the Equals method to follow one of the principles---

  Symmetry principle: for any case that references X and y, if x.equals (y), y.equals (x) should also return True.

The solution is also very simple, the front plus non-empty judgment can be, very simple, do not paste Code.

Ahvari source: http://www.cnblogs.com/selene/this article to study, research and sharing of the main, copyright belongs to the author and the blog garden, Welcome to reprint, If the text is inappropriate or wrong place also hope the great god you hesitate to point Out. If you feel that this article is helpful to you than "recommend" it! If you have better suggestions, we should discuss together with the message, and make progress together! Thank you again for your patience in reading this Post.

Reprint-write high-quality code: 151 suggestions for improving Java programs (3rd: classes, objects, and Methods ___ recommendation 41~46)

Related Article

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.