Category: Effective Java
-
[Effective Java] Item 9 – Prefer try-with-resources to try-finally
It is recommended to use try-with-resources rather than try-finally when we are working with resources that need to be closed as the resulting code is much shorter and cleaner, and the exceptions that is generates are more useful. Usage of try-with-resources Note that we can use catch clause from try-with-resources…
-
[Effective Java] Item 8 – Avoid finalizers and cleaners
What are finalizers and cleaners? Finalizers are the methods that get invoked by JVM garbage collector before the instance gets removed from the memory. From Java 9+, Cleaners are introduced and are just the same as Finalizers but overcome some of the defects of the Finalizers. Usage of finalizers By…
-
[Effective Java] Item 7 – Eliminate obsolete object references
1. Null out references once they become obsolete The Figure 1. code has a possible memory leak, as the objects popped off from the stack will not be garbage collected. This is because the stack will maintain obsolete references (References that will never be dereferenced again) to the objects that…
-
[Effective Java] Item 6 – Avoid creating unnecessary objects
1. Reuse objects Rather than creating new objects that does the same job every time, reuse the single object by using static factory methods or immutable object. For example, use Boolean.valueOf(String) which is a static factory method rather than Boolean(String). Immutable objects like String can be reused any time. For…
-
[Effective Java] Item 5 – Prefer dependency injection to hardwiring resources
Summary Classes that depends on underlying resources are not appropriate to be static utility class or singleton class. For example, the dictionary can be different maps per usage, but we cannot declare new classes every time per purpose. Pass the resource into the constructor when creating a new instance
-
[Effective Java] Item 4 – Enforce noninstantiability with a private constructor
Summary Utility classes which are made of static methods and static fields are not designed to be instantiated. Without explicit constructors, the compiler automatically creates a default constructor, which means it creates a public constructor with no parameter. Regardless of its intention, this leaves the class to be instantiable. To…
