Question

I am considering using the builder pattern described by Joshua Bloch mentioned here. I have a class which displays an Alert message and will be used by numerous applications. It can have a large number of varied options like, line1, btn txt, title, line2, timeout etc.

I like the idea of chaining the object construction with setters, but really all the app has to do after the construction is to display this alert.

Since the object created is immutable, they will have to create multiple ones for different scenarios. All calls to display these alerts are asynchronous.

Is this pattern a good idea or is better to just have static methods in the class, keep it stateless and take all the parameters in the method itself.

Was it helpful?

Solution

The article you link mentions it. One of the usecases of the builder pattern is to create a complex immutable object. One you don't want to write a huge constructor for because there are just too many parameters.

While the builder is mutable and has setters like a bean - is therefore not threadsafe - the resulting object you build is. Objects that don't have mutable state can be shared across as many threads as you wish. Nothing can modify them, so nothing can read inconsistent state.

-> safe if you don't share the builder across threads and the resulting object is threadsafe. Threadsafety of the resulting object is by the way totally independent from the way you create it.

Is this pattern a good idea or is better to just have static methods in the class, keep it stateless and take all the parameters in the method itself.

Depends on how complex the creation of the object is. Stateless is always good but with just static methods, how would you pass some sort of configuration for the alert? There must be some state somewhere to show it.

OTHER TIPS

Seems overly complex to use a builder for such a utility method. A series of static methods with apt overload signatures would do the trick fine. Not "oh my god the sky is collapsing" complexity, granted, but most consumers might consider statics "easier".

Of course, if you find yourself needing 4 overloads with (String, String, String), things change I guess...

Using the builder pattern in a concurrent system is perfectly fine.

The key decision factors are the number of parameters, and how many valid permutations of exist.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top