"Effective Java Chinese version of the second edition" reading notes

Source: Internet
Author: User
Tags sodium

Description

Here is read the "Effective Java Chinese version of the second edition" of the Reading notes, here will record some personal feeling a little bit important content, convenient for later review, may be due to personal strength reasons caused by misunderstanding, if found welcome to point out. Some individuals do not understand that will be marked with a slash.

The first chapter is the introduction, so skip.

Chapter II Creating and Destroying objects 1th: Consider replacing the constructor meaning with a static factory method

A static factory method refers to a static method that returns an instance of a class, for example:

publicstaticvalueOf(boolean b) {    return b ? Boolean.TRUE : Boolean,FALSE;}
The advantage is that there is no limit to the name of a static factory method relative to the constructor of a class.

As we all know, the constructor's method name must be the same as the class name, so for a constructor with more than one parameter type, one method is to change the order of the parameters, and the other is to add a flag to determine which construction method to execute. But this is unfriendly to the user, who must be familiar with the API or consult the development documentation. If you use the static factory method, you can give the user good hints and instructions by means of the method name.

There is no need to create a new object each time it is called.

The typical application of this sentence is that in the singleton mode of design mode, the static factory method can return the same object for repeated calls.

A static factory method can return an object of any subtype of the original return type.

The constructor method cannot use the return statement, it can only produce an object of its own class when it is used, and the static factory method can use the return statement, so there is greater flexibility in choosing the return object. There are many applications for this advantage, such as the service provider framework pattern .

Summary

You should familiarize yourself with the static factory methods and the respective strengths of the constructors and use the appropriate methods in the appropriate scenarios.

2nd: Consider using the builder when you encounter multiple constructor parameters

In the face of a class with multiple properties and the constructor method having more than one optional parameter, a common approach is to use the overlapping constructor pattern (create multiple construction methods, each with a new parameter than the previous constructor). For example, the first constructor has two mandatory parameters, the second constructor has two mandatory parameters and an optional argument, the third constructor has two mandatory parameters and two optional parameters, and so on. But when there are many parameters, the code becomes difficult to write, difficult to read, and even error prone.

Another method is to use the JavaBean mode. Because the construction process is divided into multiple invocations (the set method that invokes the property for each property's assignment), the JavaBean may be in an inconsistent state during construction, which is difficult to find.

The third approach is a form of builder mode (builder mode).

 Public classnutritionfacts {Private Final intServingsize;Private Final intservings;Private Final intcalories;Private Final intFatPrivate Final intSodiumPrivate Final intCarbohydrate; Public Static classBuilder {//Must attribute        Private Final intServingsize;Private Final intservings;//Optional Properties        Private intCalories =0;Private intFat =0;Private intSodium =0;Private intCarbohydrate =0; Public Builder(intServingsize,intServings) { This.servingsize= Servingsize; This.servings= servings; } PublicBuildersetcalories(intCalories) { This.calories= calories;return  This; } PublicBuilderSetfat(intFAT) { This.Fat= fat;return  This; } PublicBuilderSetsodium(intSodium) { This.Sodium= sodium;return  This; } PublicBuildersetcarbohydrate(intCarbohydrate) { This.Carbohydrate= Carbohydrate;return  This; } PublicNutritionfactsBuild() {return New nutritionfacts( This); }    }Private nutritionfacts(Builder builder) {servingsize = Builder.servingsize; Servings = Builder.servings; Calories = Builder.calories; Fat = Builder.Fat; Sodium = Builder.Sodium; Carbohydrate = Builder.Carbohydrate; }}//How to useNutritionfacts n =NewNutritionfacts.Builder( $,Ten).setcalories( -).Setfat( -).Build();

The builder mode is flexible enough to use a builder to create multiple identical objects, and the implementation of the required parameters and variable parameters conforms to human normal thinking. In addition, the code used is easier to read and write for users.

I've seen this approach in the Java implementation of Google's protobuf.

3rd: Hardening the Singleton property with a private constructor or enumeration type

Private construction method does not mention, here is a record of the second:

publicenum A {    INSTANCE;    publicvoidleaveTheBuilding() {...}}
4th: The ability to harden non-instancing through a private constructor

For some classes that contain only static or static properties (such as tool classes), we do not want them to be instantiated. It is well known that the compiler adds an parameterless constructor by default when an explicit construction method is missing. In order to be rigorous, we can add a private constructor, and we can abort the program by throw an exception in this constructor method.

5th: Avoid creating unnecessary objects

In general, it is better to reuse objects instead of creating new objects of the same functionality every time you need them.

In addition to reusing immutable objects, you can reuse mutable objects that are known not to be modified.

To use the basic data type, try not to use the corresponding encapsulation class.

6th: Elimination of expired object references

You can't think of a garbage collection mechanism, so you don't have to think about memory management.

For example, using an array to implement the stack, when the implementation of the stack operation, after the size-1, the top of the stack after the elements of the user is already an invalid part, but the array still has a reference to them, so the garbage collection mechanism will not recycle them. The workaround is to empty the reference when it is out of the stack.

7th: Avoid using the finalization method

Do not use the finalization method (Finalize), except in specific cases.

After the child class overrides the parent class's finalization method, the child class's finalization method does not automatically invoke the parent class's finalization method and needs to be called manually.

"Effective Java Chinese version of the second edition" reading notes

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.