Refactor Constructor invocation to builder pattern

Answered

I have found it commonplace to find places where the builder pattern should have been used but wasn't done perhaps due to someone not bother to coding the builder (or not knowing that most IDEs can generate it).

Accordingly, it would be nice if there was a way to take a not very-well self-documenting long constructor call like:

  new Member("david", "blickstein", null, "1600 Pennsylvania Ave",  null,  null,    42,   "", new Date(),  0, 0, 4, null, null)

And turn it into a builder pattern invocation:

     new Member.builder().firstname("David").lastName("blickstein").streetAddress("...").age(42).creationDate(new Date()).....

I am quite aware of the challenges here.  There is no official standard for builder patterns, and they are not self-identifying.    But a great start would be be for this to work for a few "non-standards" like:

  • Builders generated by IDEA
  • Builders generated by Lombok.
6
3 comments

Hello, 

Please tell if "Replace constructor with builder" tool solves the issue for you?  

https://www.jetbrains.com/help/idea/replace-constructor-with-builder.html

 

Thank you 

0
Avatar
Permanently deleted user

Olga Klisho   That is very close.  The problem with it is that that that refactor converts a constructor to a builder (and the invocations of the constructor).

That works if you're looking to have the IDE generate a builder that doesn't already exist.     

I'm not looking to have builders IN my code.   In fact, I'm looking to AVOID that.   To accomplish that, there is an exceedingly popular framework called Project Lombok, where you add Java annotations (in this case @Builder) and a javac/IDE Lombok plugin automatically generates them for you without having that boilerplate code actually present in the source.

So what I'm looking to do is have Lombok generate the builder (rather than IDEA) and then use an IDE refactor to convert references to constructor to be invocations of the builder.

Now what you have there MIGHT be helpful.  I imagine that I could do this process:

  1. Have the IDEA generate the builder, refactor the constructor invocations 
  2. Delete the IDEA-generated builder and add the Lombok annotation

But I think it would be better to have the IDE just be able to do the refactor-the-constructor-call part without requiring that it also generates a builder.   But the challenge there is the one I mentioned:  not all builders follow the same conventions.   There is no standard.

So your suggestion is helpful - I will probably use it.   But I still think it's a feature you should consider.

Thanks.

0

Hi Dablick,

 

Thanks for clarification, there is also an issue already created for such a feature, please follow:

https://youtrack.jetbrains.com/issue/IDEA-223530

0

Please sign in to leave a comment.