"Effective Java"------after reading summary

Source: Internet
Author: User

"Effective Java"--a summary after reading

This book is quite famous in the Java development industry. Today is finally a cursory reading ... The later thread part and the serialization section are not carefully seen due to the impatient gas mania. There is a week left in this month, and the digest is slowly summed up.

1. Static Factory method instead of constructor

    • The static factory method has a name that can accurately describe the object being returned.
    • You do not have to create a new object every time you call.
    • You can return any subclass object of the original return type.
    • It is more concise when creating instances of parameterized types, such as when calling construct HashMap, using map < String,list < String > m = hashmap.newinstance (), and map < String,list < string > M > = new HashMap < String,list < String > > ();

2. When encountering multiple constructor parameters, consider using the builder

Static factories and constructors do not scale well to a large number of optional parameters.

Using setter to set individual parameters in JavaBean mode, it is not possible to ensure consistency by verifying the validity of the constructor parameters, attempting to use an object with inconsistent state.

Builder Schema: Call the constructor with the necessary parameters, get a Builder object, set each optional parameter on the Builder object, and then call the setter-like method, and finally call the parameterless build method to generate the immutable object, new Instance.builder (required parameter). Setter (optional parameter). Build ().

The Builder pattern separates the creation and presentation of classes so that the same creation process can create different representations.

3. Avoid creating unnecessary objects

For the string type, string s = new String ("") creates a new instance each time it executes, and string s = "" does not, because for a virtual machine, the same string literal constants are reused instead of creating a new instance each time it executes.

Prefer to use basic types rather than boxed basic types to avoid unintentional automatic boxing.

4. Eliminate outdated object references

Caching takes precedence over the weakhashmap,linkedhashmap of these data structures, clearing unused items in a timely manner.

Displays canceling listeners and callbacks, or making weak references. Methods that are common to all objects

5. Overwrite equals

    • If the class has its own unique "logical equality", the superclass does not overwrite equals to achieve the desired behavior.
    • High-quality Equals method

Use the = = operator to check if the parameter is a reference to this object.

Use the instanceof operator to check if the parameter is the correct type.

Convert the parameters to the correct type.

For each key field in the class, check to see if the field in the parameter matches the corresponding field in the object.

Do not substitute the object object declared by equals with another type, because it is not able to overwrite Object.Equals, but provides an overload.

6. Always overwrite equals when hashcode

Equal objects must have equal hash codes, and if they do not overwrite hashcode together, they may cause two equal objects to not necessarily have equal hash codes, resulting in the class being unable to work with all hash-based collections.

7. Always overwrite toString

Object provides the toString, implementation is the class name [email protected]+ hash code of unsigned hexadecimal.

Self-overwriting toString, which returns all the interesting information contained in the object.

Insufficient: When the class is widely used, once the format is specified, the corresponding code is written to parse the string notation, and the string notation is embedded in the persisted data, which can then be compromised if the notation is changed.

8. Consider implementing comparable interface

If a class implements the comparable interface, it can collaborate with many generic algorithms and collections that rely on that interface, such as the ordering of collections that can be used with Array.Sort.

9. Minimize the accessibility of classes and members

    • Hide internal implementation details, effectively decouple the coupling relationships of each module
    • Access level
Private Class is only accessible within the
Package-private (default): Any class within the package can be accessed
Protected The subclass of the class that declares the member and the classes inside the package can be accessed
Public Accessible Anywhere

10, compound better than inheritance

Inheritance breaks encapsulation unless the superclass is specifically designed for expansion. Superclass if you get a new method in a subsequent release, and its subclasses overwrite the methods in the superclass that are related to the new method, an error may occur.

Composite: Adds a private domain to the new class, referencing the existing class. It does not rely on the implementation details of an existing class to forward an existing class.

11, interface is better than abstract class

Abstract classes allow implementations of certain methods, but in order to implement a type defined by an abstract class, a class must be a subclass of an abstract class and be single-inherited.

Interfaces allow us to construct a non-hierarchical type framework that securely enhances the functionality of the class.

Provides an abstract skeleton implementation class for each important interface, combining the advantages of interfaces and abstract classes (interfaces cannot contain concrete methods, abstract classes use inheritance to add functionality). They provide implementation assistance for abstract classes, but do not impose strict restrictions that are unique to abstract classes when used as type definitions.

The evolution of an abstract class is much easier than the evolution of an interface, and in subsequent versions it is always possible to add new concrete methods in the abstract class, and all subclasses of its abstract class will provide this new method, and the interface does not.

12, the interface is only used to define the type

When a class implements an interface, the interface acts as a type that can reference an instance of the class, and it is inappropriate to define the interface for any other purpose.

The bad use of the interface when the constant interface. Implementing a constant interface will result in the disclosure of such implementation details to the export API of the class, which must be implemented to ensure compatibility when the class no longer needs these constants. If a non-final class implements the constant interface, the namespace of all its subclasses will be polluted by the constants in the interface.

13. Prioritize static member classes

A static member class is the simplest nested class that can be used as a normal class, but is declared inside another class.

Each instance of a non-static member class is implicitly associated with an external instance of the outer class. An instance of a non-static member class cannot be created without an external instance. Each instance of a non-static member class contains an additional reference to an external object that causes the external instance to remain in the garbage collection.

Anonymous classes have no names and are declared and instantiated at the same time as they are used. An external instance occurs when an anonymous class appears in a non-static environment and cannot have any static members in a static environment. Anonymous classes must be kept short and readable.

A partial class, where any local variable can be declared, a local class, with a name, in a non-static environment defined only external instances, cannot contain static members, and must be kept short.

Java Learning Exchange QQ Group: 603654340 We'll learn java! together.

14. Use enum instead of int constant

An enumeration type is a type that consists of a fixed set of constants, a class that exports an instance to each enumeration constant through a public static final field, without a constructor, which is a singleton generic.

The INT enumeration pattern is not helpful in type safety and ease of use, and the printed INT enumeration variable is just a number.

The string enumeration pattern, while providing a printable string, can cause performance problems and also relies on string comparison operations.

An enumeration type can convert an enumeration into a printable string through toString, and also allow the addition of arbitrary methods and domains, and implement arbitrary interfaces.

Performance disadvantage: There is a cost of space and time when the enumeration is loaded and initialized.

15, check the validity of the parameters

For public methods, use the Javadoc @throw tag to describe the exception that is thrown when a parameter restriction is violated in the document.

For methods that are not exported (private), you can use assertions to examine the parameters. assert that if failure throws assertionexception, there is no cost overhead if it does not work.

Whenever you write a method or constructor, consider the limitations of its parameters, write these restrictions to the document, and check the display at the beginning of the method body.

16, if necessary, to carry out protective copies

For each variable parameter to a method, or to return a reference to an internally mutable component, a protective copy is required to avoid modification of the Mutable object during use.

A protective copy is performed prior to checking the validity of the parameter, and the validity check is for the object after the copy.

17, cautious use of heavy

The selection of overloaded methods is static, and the selection works at compile time, completely based on the parameter's compile-time type.

The selection of the override method is dynamic, and the selection is based on the run-time type of the object to which the method is called.

Do not export two overloaded methods with the same number of parameters, if the number of parameters is the same, at least one of the corresponding parameters in the two overloaded methods have a fundamentally different type, otherwise it should be ensured that when the same parameters are passed, all overloaded methods must behave identically.

18. Returns an array or collection of 0 lengths instead of NULL

For a method that returns null instead of a 0-length array or collection, almost every time the method is used, a null value is judged, which is tortuous and prone to error.

19, the basic type is better than the boxed basic type

The base type has only values, and the boxed base type can have the same value and different identities. Applying the = = operator to a boxed base type is almost always wrong.

The base type has only a fully functional value, and each boxed base type has a non-functional value in addition to all the functional values of its underlying type: null. When a mix of basic and boxed primitives is used in an operation, the boxed base type is automatically disassembled, and a null pointer exception is obtained if an empty object reference is automatically removed from the container.

Basic types are generally more time-and space-saving than boxing primitives, which can result in high overhead and unnecessary object creation.

20, beware of string connection performance

The string is immutable, and when two strings are concatenated, it is necessary to copy the contents of the string, and N is the square-level time to concatenate n strings. Because the nth concatenation of the string, need to n-1 the string and the nth string copy, and their spliced copy, so an-an-1 = N-1+1+n = 2n, so that you can get an = N (n-1), and O (n^2) splicing time.

21. Referencing objects via interfaces

If a suitable interface type exists, it should be declared using the interface type for parameters, return values, variables, and domains. For example, List<>vector = new vector<> (); List List = new arraylist<> (); , so the program is more flexible, and when the implementation is replaced, all you have to do is change the class in the constructor.

If there is no suitable interface, you can refer to the object in a class rather than a class interface. If you have a base class, you prefer to use the base class to refer to the object instead of its implementation class.

22. Use exceptions only for abnormal situations

Exceptions are designed to be used in exceptional situations, and do not use them for normal control flows, rather than writing APIs that break their way.

The exception-based looping pattern not only blurs the intent of the code, it reduces performance (the JVM does not optimize the code block of the exception), and it is not guaranteed to work correctly.

23. Use the exception to the recoverable condition, use run-time exception for programming error

Exception to be inspected: if you expect the caller to recover appropriately, you should use the exception that is being inspected. Forces the caller to handle the exception in a catch or propagate it by throwing the exception that is being inspected.

Unchecked exception: An extensible structure that is not required and should not be captured.

Run-time Exception: Indicates a programming error, is a subclass of RuntimeException, run-time check.

Error: Indicates a resource shortage, constraint failure, or other condition that prevented the program from continuing execution.

Design the condition that the exception throws the API: proper use of the API does not prevent this exception condition from generating & generating an exception and can immediately take useful action.

24. Throws the exception corresponding to the abstract

When a method passes an exception thrown by a low-level abstraction that is not significantly associated with the task being performed, it can cause confusion and pollute the implementation details of the higher-layer API.

Higher-level implementations should capture the lower-level exceptions, while throwing exceptions that can be interpreted in the upper-layer abstraction (exception translation).

25, try to keep the failure of atomic

Failed Atomicity: Failed method calls should keep the object in the state before it was called.

Design immutable objects that never leave existing objects in an inconsistent state.

For mutable objects:

Check the validity of the parameters before performing the operation.

Adjusts the order of the calculation process so that any part of the calculation that might fail occurs before the object state is modified.

Write a recovery code that intercepts the failures that occurred during the operation, and the objects are rolled back to the state they were before the operation started, primarily for a permanent data structure.

Performs an operation on a temporary copy of an object without destroying the state of the incoming object.

26. Simultaneous access

Synchronization prevents a thread from seeing an object in an inconsistent state, and ensures that every thread that enters the synchronization method or synchronizes the code block sees all the modifications that were previously protected by the same lock.

When multiple threads share variable data, each thread that reads or writes data must perform synchronization, which may cause activity failures and security failures.

Activity failure: Thread A changes the value of a variable, and may not be immediately reflected in line B.

Security failure: Concurrent access to shared resources causes security issues caused by state inconsistencies.

Over-synchronization can cause performance degradation, deadlock, and even indeterminate behavior.

Doing as little work as possible within the synchronization area, excessive synchronization loses parallel opportunities and limits the ability of the VM to optimize code execution

Do not invoke external methods from within the synchronization area to avoid deadlocks and data corruption.

Copyonwritearraylist all write operations by re-copying the entire underlying array, which is suitable for scenarios where read operations are much larger than write operations, where performance loss is significant when write operations are frequent.

27. Implement Serializable interface with caution

Once a class is released, the flexibility to "change the implementation of this class" is greatly reduced. If you accept the default serialization form, and later change the internal structure of the class, it will result in incompatible serialization forms. The second serialization of the corresponding stream unique identifier UID, in the declaration sequence version UID is not displayed, then change the class information, will produce a new sequence version uid, destroy its compatibility.

"Effective Java"------after reading summary

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.