Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why builder should be static inner class?

I am pretty much aware about builder pattern. Also already gone through with the builder pattern described in Item#2 in effective java of Joshua Bloch.

Here my question is - Is there any specific benefits to keep builder class inside the class which instantiates ?

We can also make it separate builder class and do the same thing.

Please be specific with your answers. AS I already know that inner class can access private members of building class and all this.

like image 227
Bhavesh Dangi Avatar asked Jul 23 '15 06:07

Bhavesh Dangi


3 Answers

First: It is defined as inner class because it is strongly related to the outer class. From oracle site:

It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. Nesting such "helper classes" makes their package more streamlined.

Second: It is defined as static because if the inner class is not static you can't instatiate it without creating an instance of the outer class.

As an additional nice behaviour you can define the constructor of the outer class private. So it is not possible to create the outer class without an explicit call to the builder.

And more as stated by JB Nizet in the comments of the question it is easier to find the builder in the javadoc searching for the outer class.

like image 195
Davide Lorenzo MARINO Avatar answered Nov 17 '22 07:11

Davide Lorenzo MARINO


You obviously already know that a nested class (whether static or not) can access private members of the surrounding class.

So the real question is:

What member is it worth to be private and to access it from a builder?

And the answer is ... the constructor! You want to make the constructor private to not allow access at all. You want to allow access to the builder instead, but the builder must call the constructor at some time to ... well ... to build it.

If you have a builder that is not nested - maybe a top level class by itself - you must make the constructor of your target class at least package private. And this is usually not wanted.

Conclusion: The builder should be a nested class.

Oh, and the answer of Davide Lorenzo MARINO is also true: Of course it is also the strong relation of the builder and its surrounding class.

like image 35
Seelenvirtuose Avatar answered Nov 17 '22 05:11

Seelenvirtuose


I think there are two reason for this.

  1. the builder can access to the outer cass private stuff so there is no need for setter that are accessible by others. -- I know that you already know.
  2. the builder class name will be the-package.Something.Builder which is self explanatory and do not cluster the package with so many classes.

Just my two cents.

like image 23
NawaMan Avatar answered Nov 17 '22 06:11

NawaMan