Valid Item 10-minimize Variability

Source: Internet
Author: User

Immutable class, that is, the class that the instance cannot be modified. All information contained in the instance remains unchanged within the lifecycle of the object.

Common examples include string, basic encapsulation class, bigdecimal, and biginteger.


Compared with the variable class, it cannot be changed to be easy to design, implement, and use, and be more stable (less prone to error) and more secure.

For example, immutable classes are essentially thread-safe. They do not need to be processed synchronously and are very convenient to use.


There are five principles for designing immutable classes:

1. No methods are provided to modify the object status. (This method also becomes mutator, which is relative to the word "mutability )")

2. Ensure that the class is not extended (extends) to prevent modifying the object state through subclass. The method to prevent expansion is usually modified using final.

3. Try to add final to all fields.

4. Try to make all fields private. Although adding final to a basic type or a field pointing to an immutable reference can prevent direct field modification, we also need to consider changing the field notation in future versions.

5. ensure exclusive access to any mutable components. That is, if a field points to a variable object, you must prevent the user from directly obtaining the variable object. This problem can be solved by returning an object copy in the constructor, Getter, and readobject.



Taking the code in the book as an example, this is a typical immutable class:

public final class Complex {private final double re;private final double im;public Complex(double re, double im) {this.re = re;this.im = im;}// Accessors with no corresponding mutatorspublic double realPart() {return re;}public double imaginaryPart() {return im;}public Complex add(Complex c) {return new Complex(re + c.re, im + c.im);}public Complex subtract(Complex c) {return new Complex(re - c.re, im - c.im);}public Complex multiply(Complex c) {return new Complex(re * c.re - im * c.im, re * c.im + im * c.re);}public Complex divide(Complex c) {double tmp = c.re * c.re + c.im * c.im;return new Complex((re * c.re + im * c.im) / tmp, (im * c.re - re* c.im)/ tmp);}@Overridepublic boolean equals(Object o) {if (o == this)return true;if (!(o instanceof Complex))return false;Complex c = (Complex) o;// See page 43 to find out why we use compare instead of ==return Double.compare(re, c.re) == 0 && Double.compare(im, c.im) == 0;}@Overridepublic int hashCode() {int result = 17 + hashDouble(re);result = 31 * result + hashDouble(im);return result;}private int hashDouble(double val) {long longBits = Double.doubleToLongBits(re);return (int) (longBits ^ (longBits >>> 32));}@Overridepublic String toString() {return "(" + re + " + " + im + "i)";}}

Since immutable objects are essentially thread-safe, immutable objects can be transmitted freely, so there is no need to consider copying instances in the constructor or getter.

However, as in the code above, a separate object is returned when you change the state of an immutable class.

If the cost of creating an object is high, this may cause performance problems.



From the standpoint of class providers, we have two ways to solve this problem:

1. Try to use the basic type for operations used inside the class.

2. If you can predict that the status will change frequently, a package-level private ancillary class will be provided accordingly. For example, stringbuilder is relative to string.



In addition, if you cannot use final to modify the immutable class for some reason, but do not want to be extended, there are other methods besides using final.

The public static factory method is used to replace all public constructors.

For example:

public static Complex valueOf(double re, double im) {return new Complex(re, im);}public static Complex valueOfPolar(double r, double theta) {return new Complex(r * Math.cos(theta), r * Math.sin(theta));}




(PS: corresponding to objective Java second edition item 15)

This article is from the "alvez. 99.9% 0b/s" blog, please be sure to keep this source http://alvez.blog.51cto.com/7711135/1440368

Valid Item 10-minimize Variability

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.