Always Remember to override toString() [Effective Java]

Default implementation of toString() in Object class is class name, '@' sign and hash code. All of it is not enough when you want to print or debug object state if the class is used by you. Even worse, if your class is used by external developers with API you provide.How to do it in … Continue reading Always Remember to override toString() [Effective Java]

Three ways of implementing singleton [Effective Java]

Singletons is a well known pattern. No matter whether you like or dislike it, it happens to be useful. Joshua Bloch in "Effective Java" reminds about three methods to implement it. One of them is not obvious, but quite interesting (Singleton as Enum) 1. Member as a public final field public class Elvis { public static … Continue reading Three ways of implementing singleton [Effective Java]

Builder instead of constructor with many (optional) parameters [Effective Java]

What is it? Builder is an internal class that is dedicated to build an instance of a type. When to use it? It is useful when you have type with optional parameters (that are not always mandatory to provide when creating object). The difference is significant when there is a plenty of params. Then instead … Continue reading Builder instead of constructor with many (optional) parameters [Effective Java]

Object construction: static factory method instead of constructor [Effective Java]

What is it Static factory method is a public static method that is used to create object - exactly the same as constructor. So when it is better than usual constructor? Advantages - unlike constructors, they have names, so you can easily distinguish and know what kind of object they actually build - unlike constructors, … Continue reading Object construction: static factory method instead of constructor [Effective Java]