Notes: 'Effective Java'
On Joshua Bloch's Effective Java book.
Joshua Bloch is a legend. His book, Effective Java, came out in 2001 and was highly praised. The second edition, which sits under my laptop as I type this, came out in 2008 to address changes introduced in Java 6. It's so well-regarded that it continues to be featured on Oracle's website, and as of now (December 2015, with Java 8 out), used and new copies are about the same price on Amazon.
I've seen this book mentioned numerous times on the Internet be recommended to Java developers who are past the beginner stage. I tend to underestimate or question my abilities, especially when it comes to software development, so I had held off getting this book until now. Gee, am I glad to have gotten it. I'm just starting it and am happy to say that I do understand most of what I'm reading, as well as the great benefits to listening to Bloch's advice. The book reminds me of Robert C. Martin's Clean Code, which is another well-regarded (and newer) book on coding best practices. But I have a feeling I'm going to like and agree with Bloch's book more. We'll see.
Thank you, experience + Udemy courses + previous books for allowing me to better understand and appreciate this book!
I'll write some notes on it below and update as I read along:
Creating and Destroying Objects
Builder pattern
For complex objects with lots of parameters (optional and mandatory).
- vs. JavaBeans pattern
- empty constructor with lots of setters
- verbose, mutable, dangerous
- vs. telescoping constructor pattern
- define multiple constructors with varying parameter lists
- does not scale well, can be confusing in client code
- creates immutable object
- easy to read
- disadvantages
- you have to create a builder object in order to create target object--may have a performance hit
- can also be verbose
- telescoping may be better for objects with 3 or fewer parameters, but do you know for sure whether that object will have more parameters in the future?
Implement Singleton as Single-element Enum Type
(This answer presumes that an "enforced" singleton is really what you want, as opposed to a de facto singleton managed by your DI framework (e.g. Guice's @Singleton), which is probably more often the right idea.)
To decompose your question into two: Is it really widely adopted? No, not as widely as it should be. Is it a good idea? Yes!
A Java enum is a class that can have only a fixed set of N instances, which are hardcoded in the source.
A singleton is a class that can have only a fixed set of N instances, which are hardcoded in the source. And
N == 1
.It's as simple as that!
Enforce noninstantiability with private constructor
---------------------------------------------------
Good especially for utility classes.
//Noninstantiable utility class
public class UtilityClass {
//Suppress default constructor for noninstantiability
private UtilityClass() { throw new AssertionError(); }
... }