This is the second article in the series of KEY POINTS FROM “EFFECTIVE JAVA” BY JOSHUA BLOCH. Let’s get to the key points.
- Encapsulation: A well-designed module should hide the implementation details cleanly separating the API details from its implementation.
- Designing a class with public mutable fields is not thread safe. Therefore, any public static final field in the class should be a primitive type or an immutable object.
- Immutable classes are easy to design, maintain and less error prone. String class in Java is immutable. Immutable objects are thread-safe and can be shared freely. In case of immutable objects, the frequently used instances can be cached using static factory methods to reduce the memory foot-print. The only disadvantage of the immutable class is separate object will be required for each state of the object.
- A Degenerate class is a class with no behavior meaning no methods.
- Favor composition over inheritance. When extended, subclass depends on the implementation details of the super class for proper functioning. Hence be judicious when choosing inheritance.
- In Decorator Pattern, the class uses composition and forwards the method calls to the composed class. Here a class decorates another class with more functionality.
- Mixin is a type that a class can implement in addition to its primary type. Interfaces are ideal for mixins.
- Simulation of multiple inheritance: Implement the interface (E.g Set) required. Create an inner class extending the skeletal implementation (E.g AbstractSet) of the interface and forward the method invocations using the inner class.
- Do not write a constant interface, an interface only with constants. Instead, use a class with the private constructor which will act as a utility class.
- Do not use tags (fields) in the class to indicate different types of object. Instead, use hierarchies to represent different type of objects.
To be continued…