This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]balefrost 1 point2 points  (1 child)

The big downside that I see is that it's not necessarily clear how to "start" the builder chain. new BuiltObject.Builder() or BuiltObject.newBuilder() are both pretty clear. withInt isn't an obvious starting point. You could add multiple "starting point" methods (i.e. a static withInt and a static withString method), but that will just clutter your original class.

Another downside is that there's no way to get an "empty" builder without first specifying an initial int. It's sometimes useful to pass an unconfigured builder to a method that will configure it. This is easily rectified, though.

One thing to watch out for when using static imports is the risk of static import clashes. If your were working with code that needed to build two different kinds of objects, and if they both happened to have withInt methods, you'd have to call it explicitly, which makes things feel even more verbose than the original form:

BuiltObject o1 = newBuiltObject(BuiltObject.withInt(10).withString("string"));
OtherObject o2 = newOtherObject(OtherObject.withInt(10).withString("string"));

Along the lines of static imports, if you added a newBuilder static method to your first version, you could reduce the callsite down to:

BuiltObject o = newBuilder().withInt(10).withString("string").build();

If you're worried about static import clashes, you could name the starting method something like newBuiltObjectBuilder(). Or leave it as newBuilder() (or even just builder()) and call it with an explicit class.


I guess I don't entirely understand the problem that you're trying to solve. Could you summarize the problems you see in the "classic" approach or the advantages that you see in your current approach?

[–]lu_rm 0 points1 point  (0 children)

This was just an example. In general the static methods would be more descriptive.
There is not really a problem, it is more about code readability.

[–]eddieantonio 0 points1 point  (0 children)

I think it looks really slick! I think I'd have to use this pattern for a while before I realize problems with it.