I'm trying to implement an immutable class, and am using the static builder pattern as defined in Effective Java.
This is a usual pattern I follow. However, I'm constrained by a third party system that requires an instance of the object to be initialised via a no-args public constructor.
It will then be 'properly' initialised by a (non-static) builder at the appropriate place.
What do people think of allowing this? It seems dirty but can't quite put my finger on how dirty!
You could also invent a solution where you let the third-party system not initialize your immutable object itself, but another intermediary object, and then you create your immutable object from that when the third-party system has done its job. That would however make your software more complex, so you'd have to decide if it's worth the trouble, and depending on the details of how everything works it might not even be possible.
The way I approach a problem like this is by having an immutable interface. For the most part, you want immutability because you want to delineate the code:- This factory module is responsible for initializing the object. All these other modules use the object but don't modify it. So, what I do is introduce an interface with only getter methods. All the modules that use the object are coded to the immutable interface. The actual implementation itself is mutable. The factory itself knows the concrete class and knows knows that the concrete class is mutable, and it takes advantage of mutability of the object to initialize it.
Jayesh A Lalwani wrote:For the most part Logger should be immutable, but it's not. You should use the static builder to get a logger, and then use it to log. The static builder reads the logging properties and initializes the logger object. Most applications don't change the logging properties at runtime. However, the reason logger is not made immutable is because the static builder itself needs setter methods.
Surely that doesn't stop the Logger class itself from being immutable?
I use Builders quite a lot when I've got complex objects, but it doesn't stop the object itself from being immutable after I've run build().
But I'm not familiar with Logger, so I may be missing something.