What has changed between Effective Java 2nd Edition and 3rd Edition

About this article

Effective Java 3rd Edition has been published. New language elements from Java 7 to Java 9 have been added, and I think that it is Lambda for the time being, but I was worried about other changes and additions. So, I compared the 2nd and 3rd editions side by side and roughly checked such places.

In this article, I've listed the places that I thought "may be characteristic!" Not about new items but about changes within existing items. [^ 1] Maybe you never feel like reading this article, but rather a reference for those who have read the 2nd edition to relearn the 3rd edition. I think it will be used like this. I think it's a lot of misunderstandings and omissions, so please enjoy looking for mistakes.

[^ 1]: I will write a separate article about new items.

Overall, the changes haven't changed much in the spirit of each item, except that the security risks of serialization have become more pronounced. In addition, Java 7 and later grammar and standard API have been added to improve writing, and the document format has been modified accordingly.

Among the tools introduced, I thought Java Microbenchmark Harness might be useful. (I haven't checked it well ...) http://openjdk.java.net/projects/code-tools/jmh/ The Item list is http://www.informit.com/store/effective-java-9780134685991. , Obtained from Sample Content.

Chapter 2: Creating and Destroying Objects

Item 1: Consider static factory methods instead of constructors

--Removed the parts that can no longer be said to be an advantage after the release of Java 7. --Contains a reference to the default methods of the Java 8 interface. ――The composition has been changed where the advantages listed in the 2nd edition are listed.

Item 2: Consider a builder when faced with many constructor parameters

--Added a sample builder with class hierarchy using recursive type parametor (Item30). --The reference to the Abstract Factory pattern has been removed.

Item 3: Enforce the singleton property with a private constructor or an enum type

--Added the mention that method references can be used by having a method called getInstance ().

Item 4: Enforce noninstantiability with a private constructor

――There is no particular characteristic change.

Item 5: Prefer dependency injection to hardwiring resources

New item

Item 6: Avoid creating unnecessary objects

--The sample code has changed to one that uses RegEx. (Maybe I didn't want to give an example of Calander or Date.)

Item 7: Eliminate obsolete object references

――There is no particular characteristic change.

Item 8: Avoid finalizers and cleaners

--The finalizer has been deprecated and a cleaner has been added, but it has also been added that it should be avoided.

Item 9: Prefer try-with-resources to try-finally

New item.

Chapter 3: Methods Common to All Objects

Item 10: Obey the general contract when overriding equals

--Google's Autovalue is introduced in the implementation of equals () hashcode (). "The automatic generation of the IDE can't keep up with class changes. It's not pretty. It's better than making it by hand." https://github.com/google/auto/tree/master/value

Item 11: Always override hashCode when you override equals

--The sample PhoneNumber class has changed to the configuration described in Item10. --It is now recommended to use Type.hashcode (f) to generate the hash value. --It also shows how to use Guava's Hashing class. https://github.com/google/guava/wiki/HashingExplained --It has been emphasized that it does not provide detailed specifications for hashcode.

Item 12: Always override toString

--Added a paragraph to static utility classes and enumerations that toString () is not needed. --Added a paragraph stating that AutoValue is recommended to generate the contents of toString ().

Item 13: Override clone judiciously

--The explanation of Object # clone () has been completely rewritten. --Added the content "The immutable class must not be cloneable, because it creates objects in vain." --It's a good idiom to use clone () to duplicate an array. Was added. (Maybe useful!)

Item 14: Consider implementing Comparable

--In the implementation of compareTo (), a static compare () method has been added to the wrapper class of each primitive type rather than using the comparison operator, so it is recommended to use it. Double.compare () Float.compare () etc. --Added the introduction of an example using Comparator.comparingInt`` Comparator.thenComparing introduced from Java8.

Chapter 4: Classes and Interfaces

Item 15: Minimize the accessibility of classes and members

--Added 4 paragraphs from P76 about Java9 module system.

Item 16: In public classes, use accessor methods, not public fields

There is no particular characteristic change.

Item 17: Minimize mutability

--Added an explanation about the difference between the functional approach (which returns the object after it has been changed by the operation) and the procedual-imperative approach (which changes itself by the operation). (P82) --Removed paragraph about static factory strengths. (Since it is the original content of Item 1, it seems to have been deleted here.) --The use of TimerTask in the example of the explanation of not creating a reinitialization method has changed to CountDownlatch. (The flawed class has changed to an alternative.)

Item 18: Favor composition over inheritance

There is no particular characteristic change.

Item 19: Design and document for inheritance or else prohibit it

--Added description about @implSpec tag.

Item 20: Prefer interfaces to abstract classes

--The fact that the default method is included in the interface is added. --Added changes to the 2nd and 3rd paragraphs of P102. --Deleted 3 paragraphs on the last page.

Item 21: Design interfaces for posterity

New item

――Let's design the interface for the future. --Use the default methods of the interface with caution. --The introduction of default methods is not always consistent with existing implementations.

Item 22: Use interfaces only to define types

--Added about being able to write numeric literals separated by underscores.

Item 23: Prefer class hierarchies to tagged classes

There is no change in the overall content.

Item 24: Favor static member classes over nonstatic

--A description of lambda was added to the description of how to use the anonymous class.

Item 25: Limit source files to a single top-level class

New item.

--Only one top-level class should be included in one source. (Although it is natural to say that.)

Chapter 5: Generics

Item 26: Don’t use raw types

――In the 2nd edition, don't use raw types in new code. It was a content that you should not use the prototype in the new code, but in the 3rd edition, the restriction of new code has been removed. (It seems to mean that the prototype should not be used, either old or new.) --The example using java.util.Date replaces BigInteger. (Is it the intention not to give it as an example?)

Item 27: Eliminate unchecked warnings

--A description that the diamond operator can be used is included.

Item 28: Prefer lists to arrays

--The sample code in the latter half has been changed to a simple one.

Item 29: Favor generic types

--One paragraph of the explanation in the middle has been rewritten to a simple content.

Item 30: Favor generic methods

--Paragraphs with content that can be covered by omitting the Java 7 generic type have been deleted. From the middle of P130 to the start of P131 to a quarter. --The sample code has been partially rewritten to an example that is conscious of lambda expressions.

Item 31: Use bounded wildcards to increase API flexibility

--The source used to describe PECS has changed. --About Explicit type parameter, it is explained that "Explicit type parameter is required before Java8". --The paragraph that says the max () method needs modification has disappeared. (It's true, but it's not the claim of this Item?)

Item 32: Combine generics and varargs judiciously

New item.

Item 33: Consider typesafe heterogeneous containers

--Almost no change. Only small corrections and supplementary explanations are included.

Chapter 6: Enums and Annotations

Item 34: Use enums instead of int constants

--Added a paragraph about the behavior when deleting the value of Enum. --Added a paragraph about not being able to access the static field of Enum from the constructor of the enum value. --Use Optional for the explanation sample source. --Added one paragraph explaining the Strategy enum pattern that defines the behavior specific to enum values. --Added a description that enums are slightly disadvantageous in terms of performance, except for resource-intensive environments such as mobile phones. --Some additions to the paragraph on when to use enums.

Item 35: Use instance fields instead of ordinals

--There is no change in the overall purpose.

Item 36: Use EnumSet instead of bit fields

--Added a paragraph that describes the disadvantages.

Item 37: Use EnumMap instead of ordinal indexing

--Some sample source modifications --The map has been changed to initialize with Stream, and some paragraphs have been added to explain it. --Several type names have changed. Harb-> Plant

Item 38: Emulate extensible enums with interfaces

--A paragraph has been added to explain an example of this pattern being used in the standard API.

Item 39: Prefer annotations to naming patterns

--A paragraph has been added to explain an example of how to write the same annotation multiple times (@Repeatable annotation) from Java8.

Item 40: Consistently use the Override annotation

--Some of the paragraphs towards the end have been modified. (About use when @Override annotation is not required)

Item 41: Use marker interfaces to define types

--Some contents have changed due to the introduction of the default method. --Some of the explanations about interface and annotation selection have been rewritten.

Chapter 7: Lambdas and Streams

New chapter! Not covered in this article.

Chapter 8: Methods

Item 49: Check parameters for validity

--Added a paragraph that all common specifications of class methods should be written in the class documentation. --Introduction of java.util.Objects`` #requireNonNull (T) in Java7. --Added a paragraph that introduces a new range checking method for java.util.Objects in Java 9.

Item 50: Make defensive copies when needed

--For the sample code, there is a paragraph to the effect that Date should not be used in Java 8 or later.

Item 51: Design method signatures carefully

--There is no change in the overall content.

Item 52: Use overloading judiciously

--Added an example of the impact of Java 8 lambdas and method references on overloading. "Don't do method overloads that take different functional interfaces as arguments."

「inexact method reference」

Reference: https://mjg123.github.io/2017/10/23/Java-Inexact-Method-References.html

Item 53: Use varargs judiciously

--All paragraphs that say "You shouldn't change a method that has an array as a parameter to a variadic argument just because it can be modified" have disappeared. (Maybe the width of the paper was adjusted, or there were few people who did this.)

Item 54: Return empty collections or arrays, not nulls

――The development of the story has changed to a structure in which the collection comes out before the array. --The content that touches on C language optimization has been deleted. (Maybe because C programmers are less likely to start Java)

Item 55: Return optionals judiciously

New item. I will omit it in this item.

Item 56: Write doc comments for all exposed API elements

There is no change in the overall claim, but various additions have been made.

--Added about doc tag added in Java8 and Java9.

(I may be grateful for how to write the document.)

Chapter 9: General Programming

Item 57: Minimize the scope of local variables

There is no change in the overall content.

Item 58: Prefer for-each loops to traditional for loops

--Added a sentence that the traditional for loop requires code modification when changing the scan target to collections and arrays. --The structure of the paragraph about the case where for-each cannot be used has changed (no change in content) --Added a sentence that Collection # removeIf can be used when filtering a collection in cases where for-each cannot be used. (It looks convenient!)

Item 59: Know and use the libraries

--In random number generation, a paragraph introducing ThreadLocalRandom has been added in Java 7 or later. --Added a paragraph to introduce ʻInputStream.html # transferTo ()` that was included in Java9. --If the library doesn't have the features you want, change the text to use a high quality third party library. (Previously, the content was to implement it yourself.)

Item 60: Avoid float and double if exact answers are required

--In the description of the sample source, it is added that a constructor that takes a String as an argument is used so that an accurate value can be entered.

Item 61: Prefer primitive types to boxed primitives

There is no change in the overall purpose.

Item 62: Avoid strings where other types are more appropriate

There is no change in the overall purpose.

Item 63: Beware the performance of string concatenation

There is no change in the overall purpose.

Item 64: Refer to objects by their interfaces

--The example in Vector has been replaced by LinkedHashSet. (Is it because Vector is old?) --The explanation by ThreadLocal has been replaced by the explanation by HashMap. (The purpose remains the same.)

Item 65: Prefer interfaces to reflection

-As a rule, one paragraph that says "In a normal application, objects should not be accessed by reflection at runtime" has been deleted. (Because the line between normal and unusual is blurred?) --Added a reference to a common parent class called ReflectiveOperationException for exceptions in reflection. (Java7 The class added in. It is suitable for multi-catch. )

Item 66: Use native methods judiciously

--Added a paragraph explaining the evolution of BigInteger since Java3. (It seems that Java 1.3 was written as Java 3. That's what it is.)

Item 67: Optimize judiciously

--Added one paragraph. "It's been nearly 20 years since this item was first written, and the operating environment of the program has changed. The combination of software elements referred to in this item makes it difficult to predict performance, and the need for measurement is relative. I went up to. " --The description that "20% of the chords are taking 80% of the time" has been changed to "10% of the chords are taking 90% of the time". (Maybe it's because it's getting bigger.) --Added reference to Java Microbenchmark Harness. http://openjdk.java.net/projects/code-tools/jmh/ (may be useful)

Item 68: Adhere to generally accepted naming conventions

--Added description about method parameter naming. --Weakened recommendations for following Java Beans naming conventions. (Because serialization is involved?)

Chapter 10: Exceptions

Item 69: Use exceptions only for exceptional conditions

--Optional is added to the discussion of whether to use the state checking method or individual values.

Item 70: Use checked exceptions for recoverable conditions and runtime exceptions for programming errors

--The structure of the paragraphs that are summarized and summarized has changed.

Item 71: Avoid unnecessary use of checked exceptions

--The paragraph about CloneNotSupportedException has been removed. --Added a paragraph on how to eliminate checked exceptions using ʻOptional`. --Added a paragraph that summarizes and summarizes.

Item 72: Favor the use of standard exceptions

--Added a paragraph stating that ʻException, RuntimeException, Throwable, ʻError should not be used directly. --Added a sentence that mentions that exception classes can be serialized for creating child classes of exception classes in the standard API. --Criteria for using ʻIllegalStateException or ʻIllegalArgumentException for selecting exception classes are now presented concretely.

Item 73: Throw exceptions appropriate to the abstraction

--There is no change in the overall purpose.

Item 74: Document all exceptions thrown by each method

--Added the description that only the main method may be throws Exception or Throwable. --Added a sentence that the exception document in the method should be written with the @throws tag.

Item 75: Include failure-capture information in detail messages

--Do not include passwords, encryption keys, etc. in detailed messages. One paragraph is added. --Added the difference between the message for users and the detailed message of exception. --Added about the constructor added by ʻIndexOutOfBoundException` in Java9

Item 76: Strive for failure atomicity

--The 3rd and 4th methods of maintaining the state of the object have been swapped. --The content has become clearer about maintenance when ʻError` occurs.

Item 77: Don’t ignore exceptions

--Added the content of ʻignored` as the variable name when the exception is intentionally ignored. --Added sample source.

Chapter 11: Concurrency

Item 78: Synchronize access to shared mutable data

--java.util.concurrent.atmic Package description was added small.

Item 79: Avoid excessive synchronization

--Added one paragraph. Added the reason why the middle BiConsumer on P318 was not used as it is. --Added one paragraph to P319. As a side note to the sample source, I added that I used an anonymous class because Lambda cannot access its own instance. --P320 One paragraph at the beginning Added that Java 7 or later multi-catch is used to catch multiple exceptions. --Added one paragraph on P322. Divided into two paragraphs. The discussion of whether to leave thread synchronization outside the class or to do it inside the class is refined. --Some additions have been made to the paragraph about synchronizing methods that access static fields.

Item 80: Prefer executors, tasks, and streams to threads

--The paragraph describing the Executor Framework as an alternative to the java.util.Timer class has been replaced with the content for the fork-join task. (Is it a matter of paper width and importance?)

Item 81: Prefer concurrency utilities to wait and notify

--There are some small additions. --In the introduction of Synchronizers, only the name of Phaser is introduced. (Introduced from Java 7) --Added a sentence that touches on accurate performance measurement. (Here again, JMH is mentioned)

Item 82: Document thread safety

――There are some minor additions, but there is no change in the overall purpose. --It is now clarified that the lock field should always be final.

Item 83: Use lazy initialization judiciously

--There is no change in the overall purpose. --Removed paragraph explaining that Double Check is now working properly with a fix in the memory model since 1.5 (Isn't we talking about Java 1.4 or earlier anymore?)

Item 84: Don’t depend on the thread scheduler

There is no change in the overall purpose.

--Deleted the paragraph about what was written in the first edition about the only usage of yield

Chapter 12: Serialization

Item 85: Prefer alternatives to Java serialization

New item

――The content of this Chapter as a whole does not recommend serialization. It is a paragraph like the outline explanation. ―― "Serialization is dangerous and should be avoided. For new systems, use JSON or Protocol Buffers."

Item 86: Implement Serializable with great caution

--Added the possibility of finalizer attack to the description of risks when implementing a class with serializable instance fields. --Several paragraphs detailing what to look out for when a class intended to inherit does not implement Serializable has disappeared. (A little less than 2 pages. Paper width problem?)

Item 87: Consider using a custom serialized form

--The performance measurement status has been corrected in the results of the 3rd edition. --Changed the description about the handling of defaultWriteObject (). (It is required to be called according to the specifications) --It is clearly stated that the serial version UID should not be changed unless you intentionally want to make it incompatible.

Item 88: Write readObject methods defensively

--There is a supplement to why the sample code casts to byte (integer literals are int, and explicit casting is required to treat numbers greater than or equal to 128 as byte. 127 It is unnecessary if the following is required. If the most significant bit when expressed in binary is 0, it is the same for ʻint and byte.) --Deleted paragraph about writeUnshared, readUnshared` method (because it was too maniac?)

Item 89: For instance control, prefer enum types to readResolve

--A proviso that "unless an attacker abuses AccessibleObject.setAccessible" is added to the descent that "Java guarantees a singleton with an enum". (When I was told that, I had neither a former nor a child, but overall I was leaning towards a pessimistic tone.)

Item 90: Consider serialization proxies instead of serialized instances

There is no change in the overall purpose.

At the end

The release dates of each edition are as follows.

Version number Release date Reference link
1st edition 2001-06-15 http://amzn.asia/j2dqKSw
2nd edition 2008-05-08 http://amzn.asia/6lVZFi4
3rd edition 2018-01-06 http://amzn.asia/hI5g2sy

The next Effective Java 4th edition is roughly predicted to be 2027, which is about 9 years later. The Java version at that time should be 30 according to the current release model [^ 2], and I can't imagine what new features it has. See you all again in 9 years. (Isn't it written anymore?)

Recommended Posts

What has changed between Effective Java 2nd Edition and 3rd Edition
Effective Java 3rd Edition Chapter 6 enums and annotations
Effective Java 3rd Edition Chapter 7 Lambda and Streams
Effective Java 3rd Edition Chapter 2 Object Creation and Disappearance
Effective Java 3rd Edition Chapter 5 Generics
Effective Java 3rd Edition Chapter 8 Methods
Effective Java 3rd Edition Chapter 9 Program General
effective java 3rd summary
Effective Java 3rd Edition Section 85 Choose Alternatives Over Java Serialization
Updates from Effective Java Third Edition 2nd Edition Personal Notes
What is the difference between Java EE and Jakarta EE?
Effective Java 3rd Edition Chapter 3 Methods Common to All Objects
I will write an excerpt of what I found interesting while reading Effective Java 3rd Edition
[Java] Difference between == and equals
[Java] What is the difference between form, entity and dto? [Bean]
Differences between "beginner" Java and Kotlin
[Java] Difference between Hashmap and HashTable
[JAVA] Difference between abstract and interface
[Java] Relationship between H2DB and JDBC
[Java] Difference between array and ArrayList
Differences between Java and .NET Framework
[Java] Difference between Closeable and AutoCloseable
[Java] Difference between StringBuffer and StringBuilder
[Java] Difference between length, length () and size ()
[Java] What are overrides and overloads?
Conversion between Kotlin nullable and Java Optional
Relationship between kotlin and java access modifiers
Difference between final and Immutable in Java
[For beginners] Difference between Java and Kotlin
[Java] Differences between instance variables and class variables
What is Java and Development Environment (MAC)
[Note] Cooperation between Java and DB (basic)
[Java] Difference between Intstream range and rangeClosed
Difference between int and Integer in Java
HashMap # putAll () behaves differently between Java 7 and Java 8