Builder pattern code generation in IntelliJ

前端 未结 11 1238
猫巷女王i
猫巷女王i 2021-01-30 01:36

Is there any way to automate writing Builder patterns in IntelliJ?

For example, given this simple class:

class Film {
   private String title;
   private         


        
相关标签:
11条回答
  • 2021-01-30 02:00

    Generate constructor of the class by right clicking on class Generate>Constructor. Then, on Windows, press is Ctrl+Shift+A to find action and type "builder", select "Replace constructor with builder.."

    0 讨论(0)
  • 2021-01-30 02:06

    Here's how to overcome the shortcomings mentioned by Mansoor Siddiqui:

    1) It needs to use an existing constructor as reference.

    Which is very easy to generate. Just hit Alt + Ins on Windows to invoke Generate menu and choose Constructor.

    2) It's not quickly accessible via the "Generate" menu (command+N on OS X)

    Just go to Settings -> Keymap, search for Builder and assign it a shortcut of your choice (if you use this functionality very often, which is rarely the case). You can assign Alt + B for example.

    Another alternative is Ctrl + Shift + A (Find Action). Start typing Builder and you'll immediately get access to the command:

    You could use this shortcut for quickly getting access to any IntelliJ IDEA feature (this helps a lot when you don't remember exactly what the command is called and where to find it).

    3) It only generates external Builder classes. As others have mentioned, it's very common to use static inner classes when implementing the builder pattern.

    I also prefer my builders as static inner classes. Unfortunately, there is no straightforward way to do it, but it's still feasible. You just have to define the nested inner class yourself (leave it empty), and when you invoke Replace Constructor with Builder dialog, choose Use existing option and select your inner class. Works like a charm! Although, it would've been easier to make this option configurable.

    0 讨论(0)
  • 2021-01-30 02:06

    I have found the Effective Inner Builder to be the best option as it adds null checks and can start with just the members defined.

    0 讨论(0)
  • 2021-01-30 02:09

    Use the Replace Constructor with Builder refactoring.

    To use this function, click on the constructor's signature in your code, then right click and select the "Refactor" menu, then click "Replace Constructor with Builder..." to bring up the dialog box to generate the code.

    0 讨论(0)
  • 2021-01-30 02:09

    As a complement to @CrazyCoder's answer, I think it's very useful to know that in the upper-right side of Replace Constructor with Builder dialog there is a configuration button that you can use to rename setters' prefix.

    0 讨论(0)
提交回复
热议问题