编程知识 cdmana.com

Notes on effective Java

2. Create and destroy objects

1. Static factory methods replace constructors

advantage :

  1. The name is clear
  2. Each call doesn't have to new object
  3. Can return any sub type object of the original return type
  4. The returned object can change with the call
  5. The class of the returned object , When writing the class of the static factory method, it may not exist
    shortcoming :
  6. private Constructors lead to , You can't have subclasses , The subclass constructor accesses the parent constructor by default

2. When there are multiple constructor parameters, you can use the builder ( Builder pattern Builder)

What is more impressive is : Before I wrote Android, I used OkHttp, The use of OkHttp Yes, it is Kotlin Written , The constructor pattern is used to instantiate objects , I thought it was Kotlin Some syntactic feature of chained calls , Later I learned that it was the design pattern

It is mainly used for multi parameter , Avoid overlapping constructors and avoid parameterless constructors to create objects in turn set In the parameter process JavaBean May be in an inconsistent state

3. Privatization of constructor or enumeration type enhancement Singleton attribute

Singleton Common implementation methods :

  1. final Modifying public static members
  2. Static factory
  3. Single element Enum

Calling private constructors through radiation , You can modify the constructor , Throw an exception when creating a second instance
In addition to implementing Serializable Interface , We need to provide readResolve, Prevent deserialization from creating new instances

4. Private constructor reinforcement is not instantiated

5. Preference is given to dependency injection to reference resources

SOLID In principle D Dependency Inversion Principle (Dependency Inversion Principle), Dependency injection is an implementation of this principle
When creating a new instance , The resource is passed to the constructor

6. Avoid creating unnecessary objects

  1. Don't use new String() Way to create String example , Use String s ="hello"; The way , Code for the same virtual machine , String literal constants are the same , The object will be reused
  2. Reuse to create high cost instances : Regular Pattern example
  3. Basic types are preferred , Automatic packing reduces performance to a certain extent
    Be careful ! When it comes to promoting protective copying , Reusing objects costs much more than creating duplicate objects

7. Clear out expired object references

  1. Stack pop It should be pop The object of is set to null
  2. One way to avoid cache memory leaks :WeakHashMap, except WeakHashMap Outside of the key of , If there is no reference to a key , Will be automatically deleted
  3. Memory leaks caused by listeners and other callbacks : Keep only their weak references , For example, save as WeakHashMap Key

8. Avoid using termination and cleanup methods

Put an end to the method (finalizer) and Method of removal (cleaner JDK9) Are unpredictable and cause performance loss
Time focused tasks should not be done in both ways
You should not rely on these two methods to update important persistent states ( such as : Free up shared resources , Maybe we haven't started releasing resources yet , And the system broke down )
TODO p25 End method attack (finalizer attack)
TODO Reasonable use :

  1. Safety net , forget close
  2. Reclaim the local peer of the object (native peer)

9. try-with-resources Prior to the try-finalyy

Realized AutoCloseable Interface

  1. grace
  2. Avoid underlying physical device exception causing the first exception to be erased by the second exception , Increase the cost of debugging

3. Methods that are common to all objects

10. Cover Equals Please pay attention to the general agreement

Without coverage ( Meet one of them )

  1. Each instance of a class is unique in nature
  2. Class does not need to provide logical equality
  3. Of the parent class equals The method is enough to use
  4. Class is private or has default permissions or determines that it will not be called to equals

Cover equals General specifications for

  1. reflexivity Not null value ,x.equals(x) by true The subclass is different from the parent equals Method , mutual equals It's against reflexivity
  2. symmetry Not null value ,x.equals(y) be equal to y.equals(x)
  3. Transitivity Not null value ,x.equals(y) by ture And y.equals(z) by true -> x.equals(z) by true Compared with the parent class, the subclass adds some functions for equals Properties of , But subclasses also use parents equals, Violation of transitivity
  4. Uniformity Not null value , Value not modified , Multiple calls equals The results should be consistent
  5. x Not null value ,x.equals(null) return false

Subclass and superclass The opposition between reflexivity and transitivity : You can't extend an instantiated class at the same time , Add new value components , At the same time, keep equals Appointment

IDEA Default subclass equals The way of writing is : Use getClass() Comparison object , Then call the parent class equals Finally, compare the properties of subclass expansion

Stream initialization Set:

 private static final Set<Point> unitCircle = Stream.of(   new Point(1, 0),   new Point(0, 1),   new Point(-1, 0),   new Point(0, -1) ).collect(Collectors.toCollection(HashSet::new));

Differentiation and analysis :instanceof getClass()==

  • instanceof Whether this object is this class Or its subclass Example
  • getClass()== Classes of runtime objects

Using composition is better than inheritance : Provide private Point Domains and shared views (view) Method

JDK Counter example :public class Timestamp extends java.util.Date, Use it in the same collection or mix it up in other ways , There may be incorrect behavior

instanceof The first operator is null So the return must be false, Use instanceof It can be omitted null Judge

Uniformity , Don't make equals Methods depend on unreliable resources ,JDK Counter example :URL equals

High-quality equals knack

  1. == Check if it is a reference to this object
  2. instanceof Check for the correct type ( At the same time, it can be ruled out null)
  3. Cast to the correct type
  4. Check each key domain
    • Basic types : ==
    • Floating point numbers :Float.compare(float,float) Double.compare(double,double) Use Float.equals or Double.equals Automatic packing reduces performance
    • Array fields :Arrays.equals
    • legal null:Objects.equals(Object,Object) Avoid throwing null pointer exceptions
    • In order of : The most likely inconsistent or least expensive domains

Be careful :

  1. Cover equals Always cover hashCode
  2. Don't over look for equivalence , For example, consider the alias form
  3. Don't put the equals The parameter is defined as not Object This is overloading, not rewriting

11. Cover equals Always cover hashCode

  1. Multiple calls to the same object hashCode Returns the same value
  2. equals(Object) equal hashCode The return integers are also equal
  3. equals(Object) It's not equal hashCode It could be equal

Object Of hashCode Method is native Method :public native int hashCode();
hashCode The note says :hashCode What is returned is the value converted from the object storage address

 As much as is reasonably practical, the hashCode method defined by class {@code Object} does return distinct integers for distinct objects. (This is typically imple.........

版权声明
本文为[Program ape Owen]所创,转载请带上原文链接,感谢
https://cdmana.com/2021/02/20210201005156029O.html

Scroll to Top