Order | Area | TOCTitle | ContentId | PageTitle | DateApproved | MetaDescription |
---|---|---|---|---|---|---|
3 | java | Refactoring | 36ee3e12-9bcc-4f01-9672-857ad2733c2d | Java code refactoring and Source Actions for Visual Studio Code | 12/9/2021 | Java code refactoring and Source Actions for Visual Studio Code |
Visual Studio Code provides many options to refactor your source code as well as Source Actions to generate code and fix issues while you're coding. To access them, click on the light bulb
💡 whenever you see it. Or right-click the editor view and pick Source Action....
- Refactoring
- Assign to variable
- Convert anonymous to nested class
- Convert to anonymous class creation
- Convert to enhanced for loop
- Convert to lambda expression
- Convert to static import
- Extract refactorings
- Inline refactorings
- Invert boolean
- Move
- Rename
- Type change
- Source Actions
- Other Code Actions supported
The goal of the Java program refactoring is to make system-wide code changes without affecting behavior of the program. The Java Language Support for VS Code provides many easily accessible refactoring options.
Refactoring commands are available from the context menu of the editor. Select the element you want to refactor, right-click to open the context menu, and choose Refactor...:
Then you will see all the available refactoring options.
Assigns an expression to a local variable or a field.
Arrays.asList("apple", "lemon", "banana");
List<String> fruits = Arrays.asList("apple", "lemon", "banana");
It can also be used to assign a parameter to a new field for unused parameter(s) in a constructor.
Converts an anonymous inner class to a member class.
Let's convert the anonymous class Interface(){...}
to a member of the class Clazz
.
publicclassClazz { publicInterfacemethod() { finalbooleanisValid = true; returnnewInterface() { publicbooleanisValid() { returnisValid; } }; } }
publicclassClazz { privatefinalclassMyInterfaceextendsInterface { privatefinalbooleanisValid; privateMyInterface(booleanisValid) { this.isValid = isValid; } publicbooleanisValid() { returnisValid; } } publicInterfacemethod() { finalbooleanisValid = true; returnnewMyInterface(isValid); } }
Converts lambda expression to anonymous class creation.
The variable runnable
is assigned with a lambda expression. Let's convert it to an anonymous class creation.
publicvoidmethod() { Runnablerunnable = () -> { // do something }; }
publicvoidmethod() { Runnablerunnable = newRunnable() { @Overridepublicvoidrun() { // do something } }; }
Also see: Convert to lambda expression
Converts the simple for
loop to for-each
style.
publicvoidorder(String[] books) { for (inti = 0; i < books.length; i++) { // do something } }
publicvoidorder(String[] books) { for (Stringbook : books) { // do something } }
Converts an anonymous class creation to the lambda expression.
Let's convert the anonymous class Runnable(){...}
to a lambda expression.
publicvoidmethod() { Runnablerunnable = newRunnable(){ @Overridepublicvoidrun() { // do something } }; }
publicvoidmethod() { Runnablerunnable = () -> { // do something }; }
Also see: Convert to anonymous class creation
Converts the field or method to static import.
Let's transform the Assert.assertEquals()
invocation to a static import.
importorg.junit.Assert; ... publicvoidtest() { Assert.assertEquals(expected, actual); }
importstaticorg.junit.Assert.assertEquals; ... publicvoidtest() { assertEquals(expected, actual); }
Creates a static final field from the selected expression and substitutes a field reference, then rewrites other places where the same expression occurs.
Let's extract the value of π: 3.14
to a constant.
publicdoublegetArea(doubler) { return3.14 * r * r; }
privatestaticfinaldoublePI = 3.14; publicdoublegetArea(doubler) { returnPI * r * r; }
Also see: Inline constant
Declares a new field and initializes it with the selected expression. The original expression is replaced with the usage of the field.
Let's extract the variable area
to a field of the class Square
.
classSquare { publicvoidcalculateArea() { intheight = 1; intwidth = 2; intarea = height * width; } }
classSquare { privateintarea; publicvoidcalculateArea() { intheight = 1; intwidth = 2; area = height * width; } }
When selecting a variable declaration, convert the variable to field.
Creates a new method containing the statements or expressions currently selected and replaces the selection with a reference to the new method. This feature is useful for cleaning up lengthy, cluttered, or overly complicated methods.
Let's extract the expression height * width
to a new method.
publicvoidmethod() { intheight = 1; intwidth = 2; intarea = height * width; }
publicvoidmethod() { intheight = 1; intwidth = 2; intarea = getArea(height, width); } privateintgetArea(intheight, intwidth) { returnheight * width; }
Also see: Inline method
Creates a new variable assigned to the expression currently selected and replaces the selection with a reference to the new variable.
Let's extract the expression platform.equalsIgnoreCase("MAC")
to a new variable.
publicvoidmethod() { if (platform.equalsIgnoreCase("MAC")) { // do something } }
publicvoidmethod() { booleanisMac = platform.equalsIgnoreCase("MAC"); if (isMac) { // do something } }
After the extraction, you can also perform a rename in the same transaction.
Also see: Inline local variable
Replaces a constant reference with its defined value.
Let's replace the constant PI
to its defined value: 3.14
.
privatestaticfinaldoublePI = 3.14; publicdoublegetArea(doubler) { returnPI * r * r; }
privatestaticfinaldoublePI = 3.14; publicdoublegetArea(doubler) { return3.14 * r * r; }
Also see: Extract to constant
Replaces redundant variable usage with its initializer.
Let's replace the variable isMac
directly to the boolean expression.
publicvoidmethod() { booleanisMac = platform.equalsIgnoreCase("MAC"); if (isMac) { // do something } }
publicvoidmethod() { if (platform.equalsIgnoreCase("MAC")) { // do something } }
Also see: Extract to local variable
Replaces calls to the method with the method’s body.
Let's replace the method getArea(int height, int width)
directly to the expression height * width
.
publicvoidmethod() { intheight = 1; intwidth = 2; intarea = getArea(height, width); } privateintgetArea(intheight, intwidth) { returnheight * width; }
publicvoidmethod() { intheight = 1; intwidth = 2; intarea = height * width; }
Also see: Extract to method
Inverts the boolean expression in the conditions.
Let's invert the boolean expression in the if statement.
publicvoidmethod(intvalue) { if (value > 5 && value < 15) { // do something } }
publicvoidmethod(intvalue) { if (value <= 5 || value >= 15) { // do something } }
Inverts the local boolean variable.
Let's invert the variable valid
.
publicvoidmethod(intvalue) { booleanvalid = value > 5 && value < 15; }
publicvoidmethod(intvalue) { booleannotValid = value <= 5 || value >= 15; }
Moves the selected elements and corrects all references to the elements (also in other files). Available actions are:
- Move class to another package
- Move static or instance method to another class
- Move inner class to a new file
Let's move the static method print()
from class Office
to class Printer
.
publicclassOffice { publicstaticvoidmain(String[] args) { print(); } publicstaticvoidprint() { System.out.println("This is printer"); } staticclassPrinter { } }
publicclassOffice { publicstaticvoidmain(String[] args) { Printer.print(); } staticclassPrinter { publicstaticvoidprint() { System.out.println("This is printer"); } } }
Move refactoring on a static method if it is used more in another class than in its own class.
Move a class to another package. Currently, move refactoring is not supported from the File Explorer.
Move an inner class to a new file.
Default shortcut: kb(editor.action.rename)
Renames the selected element and corrects all references to the elements (also in other files).
Let's rename the class Foo
to Bar
publicclassFoo { // ... } publicvoidmyMethod() { FoomyClass = newFoo(); }
publicclassBar { // ... } publicvoidmyMethod() { BarmyClass = newBar(); }
The shortcut to invoke the Rename refactoring is kb(editor.action.rename)
. When you invoke the shortcut on an identifier in the editor, a small box displays within the editor itself where you can change the identifier name. When you press kbstyle(Enter)
, all references to that identifier are changed too.
Rename refactoring is also supported from the File Explorer for folders and files. After requesting the change, a preview of impacted files will be provided and you can decide how to apply those changes.
Uses var
to declare local variables.
Strings = "";
vars = "";
Also see: Change var type to resolved type
Uses the resolved type to declare local variables.
vars = "";
Strings = "";
Also see: Change resolved type to var type
Source Actions could be used to generate common code structures and recurring elements. Some of them are Quick Fixes that help you fix code issues on the fly.
Add a constructor for the class.
Generate delegate methods
With this Source Action, all the candidates are presented to you with a checklist. You can then decide what to override or implement.
You can use this Source Action to clean up your imports. It can also deal with ambiguous imports, in that case, a dropdown list will be presented for you to pick the right one. The code line with the unresolved type is also presented to you to help you decide.
You can bulk generate getters and setters for all new member variables. If the class has more than one field, the Source Action will prompt a Quick Pick for you to select the target fields to use to generate the accessor methods.
hashCode()
and equals()
can be generated with default implementations. All the non-static member variables are listed, and you can customize the generated code using the check list.
There are two options for you to customize the generated code:
- If you use Java 7+, you can set
java.codeGeneration.hashCodeEquals.useJava7Objects
totrue
to generate shorter code that callsObjects.hash
andObjects.equals
. - You can also set
java.codeGeneration.hashCodeEquals.useInstanceof
totrue
to useinstanceOf
operator to check the object types instead of callingObject.getClass()
.
There is a new Source Action to generate the toString()
method. Customization is possible with a check list of all the member variables.
Adds final
modifier to all the variables and parameters in the current source file.
publicclassClazz { publicvoidmethod(intvalue) { booleannotValid = value > 5; if (notValid) { // do something } } }
publicclassClazz { publicvoidmethod(finalintvalue) { finalbooleannotValid = value > 5; if (notValid) { // do something } } }
This Quick Fix helps you fix non-accessible reference.
When your package name doesn't match the folder name, you have the options to either change the package name in your source code, or move the folder in the file system (even when the destination folder doesn't exist yet).
The list of Code Actions supported by VS Code keeps growing and only lists the most popular ones above. Other notable supported actions include (but not limited to):
- Create unresolved types
- Remove the
final
modifier - Remove unnecessary cast
- Remove redundant interfaces
- Add missing case labels in switch statements
- Jump to definition on break/continue
- Correct access to static elements