Skip to content

Latest commit

History

History
585 lines (438 loc) · 10.7 KB

File metadata and controls

585 lines (438 loc) · 10.7 KB

Java Clean Ups

Java clean ups are run on the current document whenever it's saved. They can fix a wide variety of issues, from code style to programming mistakes, and can even modernize the sources based on new Java language features. Here is some information on the supported cleanups and the details of what they do.

qualifyMembers

Whenever a member (field or method) of a class is accessed from within the class, prefix the access with this. This is similar to how Python requires the programmer to access members using self.

For instance:

privateintvalue;
publicintgetValue() {
returnvalue;
}

becomes:

privateintvalue;
publicintgetValue() {
returnthis.value;
}

qualifyStaticMembers

Whenever there is a static variable or function, prefix the access with the name of the class that the static variable or function belongs to.

For instance:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
out.println("moo");
returnvalue * FACTOR;
}
}

becomes:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
System.out.println("moo");
returnvalue * MyClass.FACTOR;
}
}

addOverride

When a method of a class that overrides a method from a parent class or provides an implementation for a method from an interface, add the @Override annotation.

For example:

publicclassMyRunnerimplementsRunnable {
publicvoidrun() {
System.out.println("Hello, World!");
}
}

becomes:

publicclassMyRunnerimplementsRunnable {
@Overridepublicvoidrun() {
System.out.println("Hello, World!");
}
}

addDeprecated

When a method is marked @deprecated in the Javadoc, but doesn't have the @Deprecated annotation, add the @Deprecated annotation. This only works if the compiler has been configured to mark deprecated methods without the deprecated annotation as an info/warning/error in the JDT settings.

For example:

/** * Not used anymore, please stop using. * * @deprecated */publicbooleanisAGoat() {
returnfalse;
}

becomes:

/** * Not used anymore, please stop using. * * @deprecated */@DeprecatedpublicbooleanisAGoat() {
returnfalse;
}

stringConcatToTextBlock

Appropriate String concatenations will be converted into Java Text Blocks. Appropriate String concatenations must have at least 3 non-empty substrings with one per line and the Java level must be 15 or higher. Line comments for all substrings but the last line will be lost after conversion. Spaces at the end of substrings preceding the newline will result in \s being substituted while substrings that do not end with newlines will have a \ added at the end of the line to preserve concatenation.

For example:

Stringx = "" +
"public class A {\n" +
" public void m() {\n" +
" System.out.println(\"abc\");\n" +
" }\n" +
"}";

becomes:

Stringx = """	public class A { public void m() { System.out.println("abc"); }	}""";

invertEquals

Inverts calls to Object.equals(Object) and String.equalsIgnoreCase(String) to avoid useless null pointer exception.

The caller must be nullable and the parameter must not be nullable.

By avoiding null pointer exceptions, the behavior may change.

For example:

Stringmessage = getMessage();
booleanresult1 = message.equals("text");
booleanresult2 = message.equalsIgnoreCase("text");

becomes:

Stringmessage = getMessage();
booleanresult1 = "text".equals(message);
booleanresult2 = "text".equalsIgnoreCase(message);

addFinalModifier

Use the final modifier for variable declarations wherever it is possible.

For example:

privateinti= 0;
publicvoidfoo(intj) {
intk, h;
h= 0;
}

becomes:

privatefinalinti= 0;
publicvoidfoo(finalintj) {
finalintk;
inth;
h= 0;
}

instanceofPatternMatch

Use pattern matching for the instanceof operator wherever possible. It is only applicable for Java level 15 or higher.

For example:

if (objectinstanceofInteger) {
Integeri = (Integer) object;
returni.intValue();
}

becomes:

if (objectinstanceofIntegeri) {
returni.intValue();
}

lambdaExpressionFromAnonymousClass

Convert anonymous class declarations for functional interfaces to lambda expressions wherever possible. It is only applicable for Java level 8 or above.

For example:

IntConsumerc = newIntConsumer() {
@Overridepublicvoidaccept(intvalue) {
System.out.println(i);
}
};

becomes:

IntConsumerc = i -> {
System.out.println(i);
};

switchExpression

Convert switch statements to switch expressions wherever possible. It is only applicable for Java level 14 or above.

Note : Switch statements that use control statements such as nested switch statements, if/else blocks, for/while loops are not considered as is the case for return/continue statements. All cases of the switch statement must either have a last assignment statement that sets the same variable/field as other cases, or else has a throw statement. Fall-through is allowed between cases but only if there are no other statements in between. The switch statement must have a default case unless the switch expression is an enum type and all possible enum values are represented in the cases.

For example:

inti;
switch(j) {
case1:
i = 3;
break;
case2:
i = 4;
break;
default:
i = 0;
break;
}

becomes:

inti = switch(j) {
case1 -> 3;
case2 -> 4;
default -> 0;
};

tryWithResource

Simplifies the finally block to use the try-with-resource statement.

For example:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try {
System.out.println(inputStream.read());
} finally {
inputStream.close();
}

becomes:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try (inputStream) {
System.out.println(inputStream.read());
}

lambdaExpression

Cleans up lambda expression wherever possible in the following ways:

  1. Removes unnecessary parentheses.

    For example:

    (someString) -> someString.trim().toLowerCase();

    becomes:

    someString -> someString.trim().toLowerCase();
  2. Converts lambda expression blocks to a single statement when possible.

    For example:

    someString -> {returnsomeString.trim().toLowerCase();};

    becomes:

    someString -> someString.trim().toLowerCase();
  3. Converts lambda expression to method reference.

    For example:

    () -> newArrayList<>();

    becomes:

    ArrayList::new;

organizeImports

Performs the "Organize Imports" operation.

Note : Since clean ups are meant to be applied without user feedback (eg. prompts about ambiguous types), this may leave some types unresolved. To properly resolve these ambiguous types, one can do so manually (code actions, source actions), or by calling "Organize Imports" through the command palette / key binding (shift + alt + o).

For example:

packagetest1;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

becomes:

packagetest1;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URI;
importjava.nio.file.Path;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.StringTokenizer;
importjava.util.jar.JarFile;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

renameUnusedLocalVariables

Rename unused loop variables, try-with-resource variables, catch parameters, lambda parameters, pattern variables to _.

For example:

Jj = (a, b) -> System.out.println(a);
switch (r) {
caseR(_, longl) -> {}
caseRr2 -> {}
}

becomes:

Jj = (a, _) -> System.out.println(a);
switch (r) {
caseR(_, _) -> {}
caseR_ -> {}
}

useSwitchForInstanceofPattern

Convert if/else chains to pattern matching switch statements.

For example:

inti, j;
doubled;
booleanb;
if (xinstanceofIntegerxint) {
i = xint.intValue();
} elseif (xinstanceofDoublexdouble) {
d = xdouble.doubleValue();
} elseif (xinstanceofBooleanxboolean) {
b = xboolean.booleanValue();
} else {
i = 0;
d = 0.0D;
b = false;
}

becomes:

inti, j;
doubled;
booleanb;
switch (x) {
caseIntegerxint -> i = xint.intValue();
caseDoublexdouble -> d = xdouble.doubleValue();
caseBooleanxboolean -> b = xboolean.booleanValue();
casenull, default -> {
i = 0;
d = 0.0D;
b = false;
}
}

redundantComparisonStatement

Remove redundant comparison statement.

For example:

if (i != 123) {
returni;
} else {
return123;
}

becomes:

returni;

redundantFallingThroughBlockEnd

Remove redundant end of block with jump statement.

For example:

if (0 < i) {
System.out.println("Doing something");
returni + 10;
}
returni + 10;

becomes:

if (0 < i) {
System.out.println("Doing something");
}
returni + 10;

redundantIfCondition

Remove redundant if condition.

For example:

if (isValid) {
return0;
} elseif (!isValid) {
return -1;
}

becomes:

if (isValid) {
return0;
} else {
return -1;
}

redundantModifiers

Remove redundant modifiers.

For example:

publicabstractinterfaceIFoo {
publicstaticfinalintMAGIC_NUMBER = 646;
publicabstractintfoo ();
publicintbar (intbazz);
}

becomes:

publicinterfaceIFoo {
intMAGIC_NUMBER = 646;
intfoo ();
intbar (intbazz);
}

redundantSuperCall

Remove redundant super() class in constructor.

For example:

MyClass() {
super();
}

becomes:

MyClass() {
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
vscode-java/document/_java.learnMoreAboutCleanUps.md at main · adamfgr/vscode-java · GitHub
Skip to content

Latest commit

History

History
585 lines (438 loc) · 10.7 KB

File metadata and controls

585 lines (438 loc) · 10.7 KB

Java Clean Ups

Java clean ups are run on the current document whenever it's saved. They can fix a wide variety of issues, from code style to programming mistakes, and can even modernize the sources based on new Java language features. Here is some information on the supported cleanups and the details of what they do.

qualifyMembers

Whenever a member (field or method) of a class is accessed from within the class, prefix the access with this. This is similar to how Python requires the programmer to access members using self.

For instance:

privateintvalue;
publicintgetValue() {
returnvalue;
}

becomes:

privateintvalue;
publicintgetValue() {
returnthis.value;
}

qualifyStaticMembers

Whenever there is a static variable or function, prefix the access with the name of the class that the static variable or function belongs to.

For instance:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
out.println("moo");
returnvalue * FACTOR;
}
}

becomes:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
System.out.println("moo");
returnvalue * MyClass.FACTOR;
}
}

addOverride

When a method of a class that overrides a method from a parent class or provides an implementation for a method from an interface, add the @Override annotation.

For example:

publicclassMyRunnerimplementsRunnable {
publicvoidrun() {
System.out.println("Hello, World!");
}
}

becomes:

publicclassMyRunnerimplementsRunnable {
@Overridepublicvoidrun() {
System.out.println("Hello, World!");
}
}

addDeprecated

When a method is marked @deprecated in the Javadoc, but doesn't have the @Deprecated annotation, add the @Deprecated annotation. This only works if the compiler has been configured to mark deprecated methods without the deprecated annotation as an info/warning/error in the JDT settings.

For example:

/** * Not used anymore, please stop using. * * @deprecated */publicbooleanisAGoat() {
returnfalse;
}

becomes:

/** * Not used anymore, please stop using. * * @deprecated */@DeprecatedpublicbooleanisAGoat() {
returnfalse;
}

stringConcatToTextBlock

Appropriate String concatenations will be converted into Java Text Blocks. Appropriate String concatenations must have at least 3 non-empty substrings with one per line and the Java level must be 15 or higher. Line comments for all substrings but the last line will be lost after conversion. Spaces at the end of substrings preceding the newline will result in \s being substituted while substrings that do not end with newlines will have a \ added at the end of the line to preserve concatenation.

For example:

Stringx = "" +
"public class A {\n" +
" public void m() {\n" +
" System.out.println(\"abc\");\n" +
" }\n" +
"}";

becomes:

Stringx = """	public class A { public void m() { System.out.println("abc"); }	}""";

invertEquals

Inverts calls to Object.equals(Object) and String.equalsIgnoreCase(String) to avoid useless null pointer exception.

The caller must be nullable and the parameter must not be nullable.

By avoiding null pointer exceptions, the behavior may change.

For example:

Stringmessage = getMessage();
booleanresult1 = message.equals("text");
booleanresult2 = message.equalsIgnoreCase("text");

becomes:

Stringmessage = getMessage();
booleanresult1 = "text".equals(message);
booleanresult2 = "text".equalsIgnoreCase(message);

addFinalModifier

Use the final modifier for variable declarations wherever it is possible.

For example:

privateinti= 0;
publicvoidfoo(intj) {
intk, h;
h= 0;
}

becomes:

privatefinalinti= 0;
publicvoidfoo(finalintj) {
finalintk;
inth;
h= 0;
}

instanceofPatternMatch

Use pattern matching for the instanceof operator wherever possible. It is only applicable for Java level 15 or higher.

For example:

if (objectinstanceofInteger) {
Integeri = (Integer) object;
returni.intValue();
}

becomes:

if (objectinstanceofIntegeri) {
returni.intValue();
}

lambdaExpressionFromAnonymousClass

Convert anonymous class declarations for functional interfaces to lambda expressions wherever possible. It is only applicable for Java level 8 or above.

For example:

IntConsumerc = newIntConsumer() {
@Overridepublicvoidaccept(intvalue) {
System.out.println(i);
}
};

becomes:

IntConsumerc = i -> {
System.out.println(i);
};

switchExpression

Convert switch statements to switch expressions wherever possible. It is only applicable for Java level 14 or above.

Note : Switch statements that use control statements such as nested switch statements, if/else blocks, for/while loops are not considered as is the case for return/continue statements. All cases of the switch statement must either have a last assignment statement that sets the same variable/field as other cases, or else has a throw statement. Fall-through is allowed between cases but only if there are no other statements in between. The switch statement must have a default case unless the switch expression is an enum type and all possible enum values are represented in the cases.

For example:

inti;
switch(j) {
case1:
i = 3;
break;
case2:
i = 4;
break;
default:
i = 0;
break;
}

becomes:

inti = switch(j) {
case1 -> 3;
case2 -> 4;
default -> 0;
};

tryWithResource

Simplifies the finally block to use the try-with-resource statement.

For example:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try {
System.out.println(inputStream.read());
} finally {
inputStream.close();
}

becomes:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try (inputStream) {
System.out.println(inputStream.read());
}

lambdaExpression

Cleans up lambda expression wherever possible in the following ways:

  1. Removes unnecessary parentheses.

    For example:

    (someString) -> someString.trim().toLowerCase();

    becomes:

    someString -> someString.trim().toLowerCase();
  2. Converts lambda expression blocks to a single statement when possible.

    For example:

    someString -> {returnsomeString.trim().toLowerCase();};

    becomes:

    someString -> someString.trim().toLowerCase();
  3. Converts lambda expression to method reference.

    For example:

    () -> newArrayList<>();

    becomes:

    ArrayList::new;

organizeImports

Performs the "Organize Imports" operation.

Note : Since clean ups are meant to be applied without user feedback (eg. prompts about ambiguous types), this may leave some types unresolved. To properly resolve these ambiguous types, one can do so manually (code actions, source actions), or by calling "Organize Imports" through the command palette / key binding (shift + alt + o).

For example:

packagetest1;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

becomes:

packagetest1;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URI;
importjava.nio.file.Path;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.StringTokenizer;
importjava.util.jar.JarFile;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

renameUnusedLocalVariables

Rename unused loop variables, try-with-resource variables, catch parameters, lambda parameters, pattern variables to _.

For example:

Jj = (a, b) -> System.out.println(a);
switch (r) {
caseR(_, longl) -> {}
caseRr2 -> {}
}

becomes:

Jj = (a, _) -> System.out.println(a);
switch (r) {
caseR(_, _) -> {}
caseR_ -> {}
}

useSwitchForInstanceofPattern

Convert if/else chains to pattern matching switch statements.

For example:

inti, j;
doubled;
booleanb;
if (xinstanceofIntegerxint) {
i = xint.intValue();
} elseif (xinstanceofDoublexdouble) {
d = xdouble.doubleValue();
} elseif (xinstanceofBooleanxboolean) {
b = xboolean.booleanValue();
} else {
i = 0;
d = 0.0D;
b = false;
}

becomes:

inti, j;
doubled;
booleanb;
switch (x) {
caseIntegerxint -> i = xint.intValue();
caseDoublexdouble -> d = xdouble.doubleValue();
caseBooleanxboolean -> b = xboolean.booleanValue();
casenull, default -> {
i = 0;
d = 0.0D;
b = false;
}
}

redundantComparisonStatement

Remove redundant comparison statement.

For example:

if (i != 123) {
returni;
} else {
return123;
}

becomes:

returni;

redundantFallingThroughBlockEnd

Remove redundant end of block with jump statement.

For example:

if (0 < i) {
System.out.println("Doing something");
returni + 10;
}
returni + 10;

becomes:

if (0 < i) {
System.out.println("Doing something");
}
returni + 10;

redundantIfCondition

Remove redundant if condition.

For example:

if (isValid) {
return0;
} elseif (!isValid) {
return -1;
}

becomes:

if (isValid) {
return0;
} else {
return -1;
}

redundantModifiers

Remove redundant modifiers.

For example:

publicabstractinterfaceIFoo {
publicstaticfinalintMAGIC_NUMBER = 646;
publicabstractintfoo ();
publicintbar (intbazz);
}

becomes:

publicinterfaceIFoo {
intMAGIC_NUMBER = 646;
intfoo ();
intbar (intbazz);
}

redundantSuperCall

Remove redundant super() class in constructor.

For example:

MyClass() {
super();
}

becomes:

MyClass() {
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' vscode-java/document/_java.learnMoreAboutCleanUps.md at main · adamfgr/vscode-java · GitHub
Skip to content

Latest commit

History

History
585 lines (438 loc) · 10.7 KB

File metadata and controls

585 lines (438 loc) · 10.7 KB

Java Clean Ups

Java clean ups are run on the current document whenever it's saved. They can fix a wide variety of issues, from code style to programming mistakes, and can even modernize the sources based on new Java language features. Here is some information on the supported cleanups and the details of what they do.

qualifyMembers

Whenever a member (field or method) of a class is accessed from within the class, prefix the access with this. This is similar to how Python requires the programmer to access members using self.

For instance:

privateintvalue;
publicintgetValue() {
returnvalue;
}

becomes:

privateintvalue;
publicintgetValue() {
returnthis.value;
}

qualifyStaticMembers

Whenever there is a static variable or function, prefix the access with the name of the class that the static variable or function belongs to.

For instance:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
out.println("moo");
returnvalue * FACTOR;
}
}

becomes:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
System.out.println("moo");
returnvalue * MyClass.FACTOR;
}
}

addOverride

When a method of a class that overrides a method from a parent class or provides an implementation for a method from an interface, add the @Override annotation.

For example:

publicclassMyRunnerimplementsRunnable {
publicvoidrun() {
System.out.println("Hello, World!");
}
}

becomes:

publicclassMyRunnerimplementsRunnable {
@Overridepublicvoidrun() {
System.out.println("Hello, World!");
}
}

addDeprecated

When a method is marked @deprecated in the Javadoc, but doesn't have the @Deprecated annotation, add the @Deprecated annotation. This only works if the compiler has been configured to mark deprecated methods without the deprecated annotation as an info/warning/error in the JDT settings.

For example:

/** * Not used anymore, please stop using. * * @deprecated */publicbooleanisAGoat() {
returnfalse;
}

becomes:

/** * Not used anymore, please stop using. * * @deprecated */@DeprecatedpublicbooleanisAGoat() {
returnfalse;
}

stringConcatToTextBlock

Appropriate String concatenations will be converted into Java Text Blocks. Appropriate String concatenations must have at least 3 non-empty substrings with one per line and the Java level must be 15 or higher. Line comments for all substrings but the last line will be lost after conversion. Spaces at the end of substrings preceding the newline will result in \s being substituted while substrings that do not end with newlines will have a \ added at the end of the line to preserve concatenation.

For example:

Stringx = "" +
"public class A {\n" +
" public void m() {\n" +
" System.out.println(\"abc\");\n" +
" }\n" +
"}";

becomes:

Stringx = """	public class A { public void m() { System.out.println("abc"); }	}""";

invertEquals

Inverts calls to Object.equals(Object) and String.equalsIgnoreCase(String) to avoid useless null pointer exception.

The caller must be nullable and the parameter must not be nullable.

By avoiding null pointer exceptions, the behavior may change.

For example:

Stringmessage = getMessage();
booleanresult1 = message.equals("text");
booleanresult2 = message.equalsIgnoreCase("text");

becomes:

Stringmessage = getMessage();
booleanresult1 = "text".equals(message);
booleanresult2 = "text".equalsIgnoreCase(message);

addFinalModifier

Use the final modifier for variable declarations wherever it is possible.

For example:

privateinti= 0;
publicvoidfoo(intj) {
intk, h;
h= 0;
}

becomes:

privatefinalinti= 0;
publicvoidfoo(finalintj) {
finalintk;
inth;
h= 0;
}

instanceofPatternMatch

Use pattern matching for the instanceof operator wherever possible. It is only applicable for Java level 15 or higher.

For example:

if (objectinstanceofInteger) {
Integeri = (Integer) object;
returni.intValue();
}

becomes:

if (objectinstanceofIntegeri) {
returni.intValue();
}

lambdaExpressionFromAnonymousClass

Convert anonymous class declarations for functional interfaces to lambda expressions wherever possible. It is only applicable for Java level 8 or above.

For example:

IntConsumerc = newIntConsumer() {
@Overridepublicvoidaccept(intvalue) {
System.out.println(i);
}
};

becomes:

IntConsumerc = i -> {
System.out.println(i);
};

switchExpression

Convert switch statements to switch expressions wherever possible. It is only applicable for Java level 14 or above.

Note : Switch statements that use control statements such as nested switch statements, if/else blocks, for/while loops are not considered as is the case for return/continue statements. All cases of the switch statement must either have a last assignment statement that sets the same variable/field as other cases, or else has a throw statement. Fall-through is allowed between cases but only if there are no other statements in between. The switch statement must have a default case unless the switch expression is an enum type and all possible enum values are represented in the cases.

For example:

inti;
switch(j) {
case1:
i = 3;
break;
case2:
i = 4;
break;
default:
i = 0;
break;
}

becomes:

inti = switch(j) {
case1 -> 3;
case2 -> 4;
default -> 0;
};

tryWithResource

Simplifies the finally block to use the try-with-resource statement.

For example:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try {
System.out.println(inputStream.read());
} finally {
inputStream.close();
}

becomes:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try (inputStream) {
System.out.println(inputStream.read());
}

lambdaExpression

Cleans up lambda expression wherever possible in the following ways:

  1. Removes unnecessary parentheses.

    For example:

    (someString) -> someString.trim().toLowerCase();

    becomes:

    someString -> someString.trim().toLowerCase();
  2. Converts lambda expression blocks to a single statement when possible.

    For example:

    someString -> {returnsomeString.trim().toLowerCase();};

    becomes:

    someString -> someString.trim().toLowerCase();
  3. Converts lambda expression to method reference.

    For example:

    () -> newArrayList<>();

    becomes:

    ArrayList::new;

organizeImports

Performs the "Organize Imports" operation.

Note : Since clean ups are meant to be applied without user feedback (eg. prompts about ambiguous types), this may leave some types unresolved. To properly resolve these ambiguous types, one can do so manually (code actions, source actions), or by calling "Organize Imports" through the command palette / key binding (shift + alt + o).

For example:

packagetest1;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

becomes:

packagetest1;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URI;
importjava.nio.file.Path;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.StringTokenizer;
importjava.util.jar.JarFile;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

renameUnusedLocalVariables

Rename unused loop variables, try-with-resource variables, catch parameters, lambda parameters, pattern variables to _.

For example:

Jj = (a, b) -> System.out.println(a);
switch (r) {
caseR(_, longl) -> {}
caseRr2 -> {}
}

becomes:

Jj = (a, _) -> System.out.println(a);
switch (r) {
caseR(_, _) -> {}
caseR_ -> {}
}

useSwitchForInstanceofPattern

Convert if/else chains to pattern matching switch statements.

For example:

inti, j;
doubled;
booleanb;
if (xinstanceofIntegerxint) {
i = xint.intValue();
} elseif (xinstanceofDoublexdouble) {
d = xdouble.doubleValue();
} elseif (xinstanceofBooleanxboolean) {
b = xboolean.booleanValue();
} else {
i = 0;
d = 0.0D;
b = false;
}

becomes:

inti, j;
doubled;
booleanb;
switch (x) {
caseIntegerxint -> i = xint.intValue();
caseDoublexdouble -> d = xdouble.doubleValue();
caseBooleanxboolean -> b = xboolean.booleanValue();
casenull, default -> {
i = 0;
d = 0.0D;
b = false;
}
}

redundantComparisonStatement

Remove redundant comparison statement.

For example:

if (i != 123) {
returni;
} else {
return123;
}

becomes:

returni;

redundantFallingThroughBlockEnd

Remove redundant end of block with jump statement.

For example:

if (0 < i) {
System.out.println("Doing something");
returni + 10;
}
returni + 10;

becomes:

if (0 < i) {
System.out.println("Doing something");
}
returni + 10;

redundantIfCondition

Remove redundant if condition.

For example:

if (isValid) {
return0;
} elseif (!isValid) {
return -1;
}

becomes:

if (isValid) {
return0;
} else {
return -1;
}

redundantModifiers

Remove redundant modifiers.

For example:

publicabstractinterfaceIFoo {
publicstaticfinalintMAGIC_NUMBER = 646;
publicabstractintfoo ();
publicintbar (intbazz);
}

becomes:

publicinterfaceIFoo {
intMAGIC_NUMBER = 646;
intfoo ();
intbar (intbazz);
}

redundantSuperCall

Remove redundant super() class in constructor.

For example:

MyClass() {
super();
}

becomes:

MyClass() {
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' vscode-java/document/_java.learnMoreAboutCleanUps.md at main · adamfgr/vscode-java · GitHub
Skip to content

Latest commit

History

History
585 lines (438 loc) · 10.7 KB

File metadata and controls

585 lines (438 loc) · 10.7 KB

Java Clean Ups

Java clean ups are run on the current document whenever it's saved. They can fix a wide variety of issues, from code style to programming mistakes, and can even modernize the sources based on new Java language features. Here is some information on the supported cleanups and the details of what they do.

qualifyMembers

Whenever a member (field or method) of a class is accessed from within the class, prefix the access with this. This is similar to how Python requires the programmer to access members using self.

For instance:

privateintvalue;
publicintgetValue() {
returnvalue;
}

becomes:

privateintvalue;
publicintgetValue() {
returnthis.value;
}

qualifyStaticMembers

Whenever there is a static variable or function, prefix the access with the name of the class that the static variable or function belongs to.

For instance:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
out.println("moo");
returnvalue * FACTOR;
}
}

becomes:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
System.out.println("moo");
returnvalue * MyClass.FACTOR;
}
}

addOverride

When a method of a class that overrides a method from a parent class or provides an implementation for a method from an interface, add the @Override annotation.

For example:

publicclassMyRunnerimplementsRunnable {
publicvoidrun() {
System.out.println("Hello, World!");
}
}

becomes:

publicclassMyRunnerimplementsRunnable {
@Overridepublicvoidrun() {
System.out.println("Hello, World!");
}
}

addDeprecated

When a method is marked @deprecated in the Javadoc, but doesn't have the @Deprecated annotation, add the @Deprecated annotation. This only works if the compiler has been configured to mark deprecated methods without the deprecated annotation as an info/warning/error in the JDT settings.

For example:

/** * Not used anymore, please stop using. * * @deprecated */publicbooleanisAGoat() {
returnfalse;
}

becomes:

/** * Not used anymore, please stop using. * * @deprecated */@DeprecatedpublicbooleanisAGoat() {
returnfalse;
}

stringConcatToTextBlock

Appropriate String concatenations will be converted into Java Text Blocks. Appropriate String concatenations must have at least 3 non-empty substrings with one per line and the Java level must be 15 or higher. Line comments for all substrings but the last line will be lost after conversion. Spaces at the end of substrings preceding the newline will result in \s being substituted while substrings that do not end with newlines will have a \ added at the end of the line to preserve concatenation.

For example:

Stringx = "" +
"public class A {\n" +
" public void m() {\n" +
" System.out.println(\"abc\");\n" +
" }\n" +
"}";

becomes:

Stringx = """	public class A { public void m() { System.out.println("abc"); }	}""";

invertEquals

Inverts calls to Object.equals(Object) and String.equalsIgnoreCase(String) to avoid useless null pointer exception.

The caller must be nullable and the parameter must not be nullable.

By avoiding null pointer exceptions, the behavior may change.

For example:

Stringmessage = getMessage();
booleanresult1 = message.equals("text");
booleanresult2 = message.equalsIgnoreCase("text");

becomes:

Stringmessage = getMessage();
booleanresult1 = "text".equals(message);
booleanresult2 = "text".equalsIgnoreCase(message);

addFinalModifier

Use the final modifier for variable declarations wherever it is possible.

For example:

privateinti= 0;
publicvoidfoo(intj) {
intk, h;
h= 0;
}

becomes:

privatefinalinti= 0;
publicvoidfoo(finalintj) {
finalintk;
inth;
h= 0;
}

instanceofPatternMatch

Use pattern matching for the instanceof operator wherever possible. It is only applicable for Java level 15 or higher.

For example:

if (objectinstanceofInteger) {
Integeri = (Integer) object;
returni.intValue();
}

becomes:

if (objectinstanceofIntegeri) {
returni.intValue();
}

lambdaExpressionFromAnonymousClass

Convert anonymous class declarations for functional interfaces to lambda expressions wherever possible. It is only applicable for Java level 8 or above.

For example:

IntConsumerc = newIntConsumer() {
@Overridepublicvoidaccept(intvalue) {
System.out.println(i);
}
};

becomes:

IntConsumerc = i -> {
System.out.println(i);
};

switchExpression

Convert switch statements to switch expressions wherever possible. It is only applicable for Java level 14 or above.

Note : Switch statements that use control statements such as nested switch statements, if/else blocks, for/while loops are not considered as is the case for return/continue statements. All cases of the switch statement must either have a last assignment statement that sets the same variable/field as other cases, or else has a throw statement. Fall-through is allowed between cases but only if there are no other statements in between. The switch statement must have a default case unless the switch expression is an enum type and all possible enum values are represented in the cases.

For example:

inti;
switch(j) {
case1:
i = 3;
break;
case2:
i = 4;
break;
default:
i = 0;
break;
}

becomes:

inti = switch(j) {
case1 -> 3;
case2 -> 4;
default -> 0;
};

tryWithResource

Simplifies the finally block to use the try-with-resource statement.

For example:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try {
System.out.println(inputStream.read());
} finally {
inputStream.close();
}

becomes:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try (inputStream) {
System.out.println(inputStream.read());
}

lambdaExpression

Cleans up lambda expression wherever possible in the following ways:

  1. Removes unnecessary parentheses.

    For example:

    (someString) -> someString.trim().toLowerCase();

    becomes:

    someString -> someString.trim().toLowerCase();
  2. Converts lambda expression blocks to a single statement when possible.

    For example:

    someString -> {returnsomeString.trim().toLowerCase();};

    becomes:

    someString -> someString.trim().toLowerCase();
  3. Converts lambda expression to method reference.

    For example:

    () -> newArrayList<>();

    becomes:

    ArrayList::new;

organizeImports

Performs the "Organize Imports" operation.

Note : Since clean ups are meant to be applied without user feedback (eg. prompts about ambiguous types), this may leave some types unresolved. To properly resolve these ambiguous types, one can do so manually (code actions, source actions), or by calling "Organize Imports" through the command palette / key binding (shift + alt + o).

For example:

packagetest1;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

becomes:

packagetest1;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URI;
importjava.nio.file.Path;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.StringTokenizer;
importjava.util.jar.JarFile;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

renameUnusedLocalVariables

Rename unused loop variables, try-with-resource variables, catch parameters, lambda parameters, pattern variables to _.

For example:

Jj = (a, b) -> System.out.println(a);
switch (r) {
caseR(_, longl) -> {}
caseRr2 -> {}
}

becomes:

Jj = (a, _) -> System.out.println(a);
switch (r) {
caseR(_, _) -> {}
caseR_ -> {}
}

useSwitchForInstanceofPattern

Convert if/else chains to pattern matching switch statements.

For example:

inti, j;
doubled;
booleanb;
if (xinstanceofIntegerxint) {
i = xint.intValue();
} elseif (xinstanceofDoublexdouble) {
d = xdouble.doubleValue();
} elseif (xinstanceofBooleanxboolean) {
b = xboolean.booleanValue();
} else {
i = 0;
d = 0.0D;
b = false;
}

becomes:

inti, j;
doubled;
booleanb;
switch (x) {
caseIntegerxint -> i = xint.intValue();
caseDoublexdouble -> d = xdouble.doubleValue();
caseBooleanxboolean -> b = xboolean.booleanValue();
casenull, default -> {
i = 0;
d = 0.0D;
b = false;
}
}

redundantComparisonStatement

Remove redundant comparison statement.

For example:

if (i != 123) {
returni;
} else {
return123;
}

becomes:

returni;

redundantFallingThroughBlockEnd

Remove redundant end of block with jump statement.

For example:

if (0 < i) {
System.out.println("Doing something");
returni + 10;
}
returni + 10;

becomes:

if (0 < i) {
System.out.println("Doing something");
}
returni + 10;

redundantIfCondition

Remove redundant if condition.

For example:

if (isValid) {
return0;
} elseif (!isValid) {
return -1;
}

becomes:

if (isValid) {
return0;
} else {
return -1;
}

redundantModifiers

Remove redundant modifiers.

For example:

publicabstractinterfaceIFoo {
publicstaticfinalintMAGIC_NUMBER = 646;
publicabstractintfoo ();
publicintbar (intbazz);
}

becomes:

publicinterfaceIFoo {
intMAGIC_NUMBER = 646;
intfoo ();
intbar (intbazz);
}

redundantSuperCall

Remove redundant super() class in constructor.

For example:

MyClass() {
super();
}

becomes:

MyClass() {
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' vscode-java/document/_java.learnMoreAboutCleanUps.md at main · adamfgr/vscode-java · GitHub
Skip to content

Latest commit

History

History
585 lines (438 loc) · 10.7 KB

File metadata and controls

585 lines (438 loc) · 10.7 KB

Java Clean Ups

Java clean ups are run on the current document whenever it's saved. They can fix a wide variety of issues, from code style to programming mistakes, and can even modernize the sources based on new Java language features. Here is some information on the supported cleanups and the details of what they do.

qualifyMembers

Whenever a member (field or method) of a class is accessed from within the class, prefix the access with this. This is similar to how Python requires the programmer to access members using self.

For instance:

privateintvalue;
publicintgetValue() {
returnvalue;
}

becomes:

privateintvalue;
publicintgetValue() {
returnthis.value;
}

qualifyStaticMembers

Whenever there is a static variable or function, prefix the access with the name of the class that the static variable or function belongs to.

For instance:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
out.println("moo");
returnvalue * FACTOR;
}
}

becomes:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
System.out.println("moo");
returnvalue * MyClass.FACTOR;
}
}

addOverride

When a method of a class that overrides a method from a parent class or provides an implementation for a method from an interface, add the @Override annotation.

For example:

publicclassMyRunnerimplementsRunnable {
publicvoidrun() {
System.out.println("Hello, World!");
}
}

becomes:

publicclassMyRunnerimplementsRunnable {
@Overridepublicvoidrun() {
System.out.println("Hello, World!");
}
}

addDeprecated

When a method is marked @deprecated in the Javadoc, but doesn't have the @Deprecated annotation, add the @Deprecated annotation. This only works if the compiler has been configured to mark deprecated methods without the deprecated annotation as an info/warning/error in the JDT settings.

For example:

/** * Not used anymore, please stop using. * * @deprecated */publicbooleanisAGoat() {
returnfalse;
}

becomes:

/** * Not used anymore, please stop using. * * @deprecated */@DeprecatedpublicbooleanisAGoat() {
returnfalse;
}

stringConcatToTextBlock

Appropriate String concatenations will be converted into Java Text Blocks. Appropriate String concatenations must have at least 3 non-empty substrings with one per line and the Java level must be 15 or higher. Line comments for all substrings but the last line will be lost after conversion. Spaces at the end of substrings preceding the newline will result in \s being substituted while substrings that do not end with newlines will have a \ added at the end of the line to preserve concatenation.

For example:

Stringx = "" +
"public class A {\n" +
" public void m() {\n" +
" System.out.println(\"abc\");\n" +
" }\n" +
"}";

becomes:

Stringx = """	public class A { public void m() { System.out.println("abc"); }	}""";

invertEquals

Inverts calls to Object.equals(Object) and String.equalsIgnoreCase(String) to avoid useless null pointer exception.

The caller must be nullable and the parameter must not be nullable.

By avoiding null pointer exceptions, the behavior may change.

For example:

Stringmessage = getMessage();
booleanresult1 = message.equals("text");
booleanresult2 = message.equalsIgnoreCase("text");

becomes:

Stringmessage = getMessage();
booleanresult1 = "text".equals(message);
booleanresult2 = "text".equalsIgnoreCase(message);

addFinalModifier

Use the final modifier for variable declarations wherever it is possible.

For example:

privateinti= 0;
publicvoidfoo(intj) {
intk, h;
h= 0;
}

becomes:

privatefinalinti= 0;
publicvoidfoo(finalintj) {
finalintk;
inth;
h= 0;
}

instanceofPatternMatch

Use pattern matching for the instanceof operator wherever possible. It is only applicable for Java level 15 or higher.

For example:

if (objectinstanceofInteger) {
Integeri = (Integer) object;
returni.intValue();
}

becomes:

if (objectinstanceofIntegeri) {
returni.intValue();
}

lambdaExpressionFromAnonymousClass

Convert anonymous class declarations for functional interfaces to lambda expressions wherever possible. It is only applicable for Java level 8 or above.

For example:

IntConsumerc = newIntConsumer() {
@Overridepublicvoidaccept(intvalue) {
System.out.println(i);
}
};

becomes:

IntConsumerc = i -> {
System.out.println(i);
};

switchExpression

Convert switch statements to switch expressions wherever possible. It is only applicable for Java level 14 or above.

Note : Switch statements that use control statements such as nested switch statements, if/else blocks, for/while loops are not considered as is the case for return/continue statements. All cases of the switch statement must either have a last assignment statement that sets the same variable/field as other cases, or else has a throw statement. Fall-through is allowed between cases but only if there are no other statements in between. The switch statement must have a default case unless the switch expression is an enum type and all possible enum values are represented in the cases.

For example:

inti;
switch(j) {
case1:
i = 3;
break;
case2:
i = 4;
break;
default:
i = 0;
break;
}

becomes:

inti = switch(j) {
case1 -> 3;
case2 -> 4;
default -> 0;
};

tryWithResource

Simplifies the finally block to use the try-with-resource statement.

For example:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try {
System.out.println(inputStream.read());
} finally {
inputStream.close();
}

becomes:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try (inputStream) {
System.out.println(inputStream.read());
}

lambdaExpression

Cleans up lambda expression wherever possible in the following ways:

  1. Removes unnecessary parentheses.

    For example:

    (someString) -> someString.trim().toLowerCase();

    becomes:

    someString -> someString.trim().toLowerCase();
  2. Converts lambda expression blocks to a single statement when possible.

    For example:

    someString -> {returnsomeString.trim().toLowerCase();};

    becomes:

    someString -> someString.trim().toLowerCase();
  3. Converts lambda expression to method reference.

    For example:

    () -> newArrayList<>();

    becomes:

    ArrayList::new;

organizeImports

Performs the "Organize Imports" operation.

Note : Since clean ups are meant to be applied without user feedback (eg. prompts about ambiguous types), this may leave some types unresolved. To properly resolve these ambiguous types, one can do so manually (code actions, source actions), or by calling "Organize Imports" through the command palette / key binding (shift + alt + o).

For example:

packagetest1;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

becomes:

packagetest1;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URI;
importjava.nio.file.Path;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.StringTokenizer;
importjava.util.jar.JarFile;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

renameUnusedLocalVariables

Rename unused loop variables, try-with-resource variables, catch parameters, lambda parameters, pattern variables to _.

For example:

Jj = (a, b) -> System.out.println(a);
switch (r) {
caseR(_, longl) -> {}
caseRr2 -> {}
}

becomes:

Jj = (a, _) -> System.out.println(a);
switch (r) {
caseR(_, _) -> {}
caseR_ -> {}
}

useSwitchForInstanceofPattern

Convert if/else chains to pattern matching switch statements.

For example:

inti, j;
doubled;
booleanb;
if (xinstanceofIntegerxint) {
i = xint.intValue();
} elseif (xinstanceofDoublexdouble) {
d = xdouble.doubleValue();
} elseif (xinstanceofBooleanxboolean) {
b = xboolean.booleanValue();
} else {
i = 0;
d = 0.0D;
b = false;
}

becomes:

inti, j;
doubled;
booleanb;
switch (x) {
caseIntegerxint -> i = xint.intValue();
caseDoublexdouble -> d = xdouble.doubleValue();
caseBooleanxboolean -> b = xboolean.booleanValue();
casenull, default -> {
i = 0;
d = 0.0D;
b = false;
}
}

redundantComparisonStatement

Remove redundant comparison statement.

For example:

if (i != 123) {
returni;
} else {
return123;
}

becomes:

returni;

redundantFallingThroughBlockEnd

Remove redundant end of block with jump statement.

For example:

if (0 < i) {
System.out.println("Doing something");
returni + 10;
}
returni + 10;

becomes:

if (0 < i) {
System.out.println("Doing something");
}
returni + 10;

redundantIfCondition

Remove redundant if condition.

For example:

if (isValid) {
return0;
} elseif (!isValid) {
return -1;
}

becomes:

if (isValid) {
return0;
} else {
return -1;
}

redundantModifiers

Remove redundant modifiers.

For example:

publicabstractinterfaceIFoo {
publicstaticfinalintMAGIC_NUMBER = 646;
publicabstractintfoo ();
publicintbar (intbazz);
}

becomes:

publicinterfaceIFoo {
intMAGIC_NUMBER = 646;
intfoo ();
intbar (intbazz);
}

redundantSuperCall

Remove redundant super() class in constructor.

For example:

MyClass() {
super();
}

becomes:

MyClass() {
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' vscode-java/document/_java.learnMoreAboutCleanUps.md at main · adamfgr/vscode-java · GitHub
Skip to content

Latest commit

History

History
585 lines (438 loc) · 10.7 KB

File metadata and controls

585 lines (438 loc) · 10.7 KB

Java Clean Ups

Java clean ups are run on the current document whenever it's saved. They can fix a wide variety of issues, from code style to programming mistakes, and can even modernize the sources based on new Java language features. Here is some information on the supported cleanups and the details of what they do.

qualifyMembers

Whenever a member (field or method) of a class is accessed from within the class, prefix the access with this. This is similar to how Python requires the programmer to access members using self.

For instance:

privateintvalue;
publicintgetValue() {
returnvalue;
}

becomes:

privateintvalue;
publicintgetValue() {
returnthis.value;
}

qualifyStaticMembers

Whenever there is a static variable or function, prefix the access with the name of the class that the static variable or function belongs to.

For instance:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
out.println("moo");
returnvalue * FACTOR;
}
}

becomes:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
System.out.println("moo");
returnvalue * MyClass.FACTOR;
}
}

addOverride

When a method of a class that overrides a method from a parent class or provides an implementation for a method from an interface, add the @Override annotation.

For example:

publicclassMyRunnerimplementsRunnable {
publicvoidrun() {
System.out.println("Hello, World!");
}
}

becomes:

publicclassMyRunnerimplementsRunnable {
@Overridepublicvoidrun() {
System.out.println("Hello, World!");
}
}

addDeprecated

When a method is marked @deprecated in the Javadoc, but doesn't have the @Deprecated annotation, add the @Deprecated annotation. This only works if the compiler has been configured to mark deprecated methods without the deprecated annotation as an info/warning/error in the JDT settings.

For example:

/** * Not used anymore, please stop using. * * @deprecated */publicbooleanisAGoat() {
returnfalse;
}

becomes:

/** * Not used anymore, please stop using. * * @deprecated */@DeprecatedpublicbooleanisAGoat() {
returnfalse;
}

stringConcatToTextBlock

Appropriate String concatenations will be converted into Java Text Blocks. Appropriate String concatenations must have at least 3 non-empty substrings with one per line and the Java level must be 15 or higher. Line comments for all substrings but the last line will be lost after conversion. Spaces at the end of substrings preceding the newline will result in \s being substituted while substrings that do not end with newlines will have a \ added at the end of the line to preserve concatenation.

For example:

Stringx = "" +
"public class A {\n" +
" public void m() {\n" +
" System.out.println(\"abc\");\n" +
" }\n" +
"}";

becomes:

Stringx = """	public class A { public void m() { System.out.println("abc"); }	}""";

invertEquals

Inverts calls to Object.equals(Object) and String.equalsIgnoreCase(String) to avoid useless null pointer exception.

The caller must be nullable and the parameter must not be nullable.

By avoiding null pointer exceptions, the behavior may change.

For example:

Stringmessage = getMessage();
booleanresult1 = message.equals("text");
booleanresult2 = message.equalsIgnoreCase("text");

becomes:

Stringmessage = getMessage();
booleanresult1 = "text".equals(message);
booleanresult2 = "text".equalsIgnoreCase(message);

addFinalModifier

Use the final modifier for variable declarations wherever it is possible.

For example:

privateinti= 0;
publicvoidfoo(intj) {
intk, h;
h= 0;
}

becomes:

privatefinalinti= 0;
publicvoidfoo(finalintj) {
finalintk;
inth;
h= 0;
}

instanceofPatternMatch

Use pattern matching for the instanceof operator wherever possible. It is only applicable for Java level 15 or higher.

For example:

if (objectinstanceofInteger) {
Integeri = (Integer) object;
returni.intValue();
}

becomes:

if (objectinstanceofIntegeri) {
returni.intValue();
}

lambdaExpressionFromAnonymousClass

Convert anonymous class declarations for functional interfaces to lambda expressions wherever possible. It is only applicable for Java level 8 or above.

For example:

IntConsumerc = newIntConsumer() {
@Overridepublicvoidaccept(intvalue) {
System.out.println(i);
}
};

becomes:

IntConsumerc = i -> {
System.out.println(i);
};

switchExpression

Convert switch statements to switch expressions wherever possible. It is only applicable for Java level 14 or above.

Note : Switch statements that use control statements such as nested switch statements, if/else blocks, for/while loops are not considered as is the case for return/continue statements. All cases of the switch statement must either have a last assignment statement that sets the same variable/field as other cases, or else has a throw statement. Fall-through is allowed between cases but only if there are no other statements in between. The switch statement must have a default case unless the switch expression is an enum type and all possible enum values are represented in the cases.

For example:

inti;
switch(j) {
case1:
i = 3;
break;
case2:
i = 4;
break;
default:
i = 0;
break;
}

becomes:

inti = switch(j) {
case1 -> 3;
case2 -> 4;
default -> 0;
};

tryWithResource

Simplifies the finally block to use the try-with-resource statement.

For example:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try {
System.out.println(inputStream.read());
} finally {
inputStream.close();
}

becomes:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try (inputStream) {
System.out.println(inputStream.read());
}

lambdaExpression

Cleans up lambda expression wherever possible in the following ways:

  1. Removes unnecessary parentheses.

    For example:

    (someString) -> someString.trim().toLowerCase();

    becomes:

    someString -> someString.trim().toLowerCase();
  2. Converts lambda expression blocks to a single statement when possible.

    For example:

    someString -> {returnsomeString.trim().toLowerCase();};

    becomes:

    someString -> someString.trim().toLowerCase();
  3. Converts lambda expression to method reference.

    For example:

    () -> newArrayList<>();

    becomes:

    ArrayList::new;

organizeImports

Performs the "Organize Imports" operation.

Note : Since clean ups are meant to be applied without user feedback (eg. prompts about ambiguous types), this may leave some types unresolved. To properly resolve these ambiguous types, one can do so manually (code actions, source actions), or by calling "Organize Imports" through the command palette / key binding (shift + alt + o).

For example:

packagetest1;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

becomes:

packagetest1;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URI;
importjava.nio.file.Path;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.StringTokenizer;
importjava.util.jar.JarFile;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

renameUnusedLocalVariables

Rename unused loop variables, try-with-resource variables, catch parameters, lambda parameters, pattern variables to _.

For example:

Jj = (a, b) -> System.out.println(a);
switch (r) {
caseR(_, longl) -> {}
caseRr2 -> {}
}

becomes:

Jj = (a, _) -> System.out.println(a);
switch (r) {
caseR(_, _) -> {}
caseR_ -> {}
}

useSwitchForInstanceofPattern

Convert if/else chains to pattern matching switch statements.

For example:

inti, j;
doubled;
booleanb;
if (xinstanceofIntegerxint) {
i = xint.intValue();
} elseif (xinstanceofDoublexdouble) {
d = xdouble.doubleValue();
} elseif (xinstanceofBooleanxboolean) {
b = xboolean.booleanValue();
} else {
i = 0;
d = 0.0D;
b = false;
}

becomes:

inti, j;
doubled;
booleanb;
switch (x) {
caseIntegerxint -> i = xint.intValue();
caseDoublexdouble -> d = xdouble.doubleValue();
caseBooleanxboolean -> b = xboolean.booleanValue();
casenull, default -> {
i = 0;
d = 0.0D;
b = false;
}
}

redundantComparisonStatement

Remove redundant comparison statement.

For example:

if (i != 123) {
returni;
} else {
return123;
}

becomes:

returni;

redundantFallingThroughBlockEnd

Remove redundant end of block with jump statement.

For example:

if (0 < i) {
System.out.println("Doing something");
returni + 10;
}
returni + 10;

becomes:

if (0 < i) {
System.out.println("Doing something");
}
returni + 10;

redundantIfCondition

Remove redundant if condition.

For example:

if (isValid) {
return0;
} elseif (!isValid) {
return -1;
}

becomes:

if (isValid) {
return0;
} else {
return -1;
}

redundantModifiers

Remove redundant modifiers.

For example:

publicabstractinterfaceIFoo {
publicstaticfinalintMAGIC_NUMBER = 646;
publicabstractintfoo ();
publicintbar (intbazz);
}

becomes:

publicinterfaceIFoo {
intMAGIC_NUMBER = 646;
intfoo ();
intbar (intbazz);
}

redundantSuperCall

Remove redundant super() class in constructor.

For example:

MyClass() {
super();
}

becomes:

MyClass() {
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' vscode-java/document/_java.learnMoreAboutCleanUps.md at main · adamfgr/vscode-java · GitHub
Skip to content

Latest commit

History

History
585 lines (438 loc) · 10.7 KB

File metadata and controls

585 lines (438 loc) · 10.7 KB

Java Clean Ups

Java clean ups are run on the current document whenever it's saved. They can fix a wide variety of issues, from code style to programming mistakes, and can even modernize the sources based on new Java language features. Here is some information on the supported cleanups and the details of what they do.

qualifyMembers

Whenever a member (field or method) of a class is accessed from within the class, prefix the access with this. This is similar to how Python requires the programmer to access members using self.

For instance:

privateintvalue;
publicintgetValue() {
returnvalue;
}

becomes:

privateintvalue;
publicintgetValue() {
returnthis.value;
}

qualifyStaticMembers

Whenever there is a static variable or function, prefix the access with the name of the class that the static variable or function belongs to.

For instance:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
out.println("moo");
returnvalue * FACTOR;
}
}

becomes:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
System.out.println("moo");
returnvalue * MyClass.FACTOR;
}
}

addOverride

When a method of a class that overrides a method from a parent class or provides an implementation for a method from an interface, add the @Override annotation.

For example:

publicclassMyRunnerimplementsRunnable {
publicvoidrun() {
System.out.println("Hello, World!");
}
}

becomes:

publicclassMyRunnerimplementsRunnable {
@Overridepublicvoidrun() {
System.out.println("Hello, World!");
}
}

addDeprecated

When a method is marked @deprecated in the Javadoc, but doesn't have the @Deprecated annotation, add the @Deprecated annotation. This only works if the compiler has been configured to mark deprecated methods without the deprecated annotation as an info/warning/error in the JDT settings.

For example:

/** * Not used anymore, please stop using. * * @deprecated */publicbooleanisAGoat() {
returnfalse;
}

becomes:

/** * Not used anymore, please stop using. * * @deprecated */@DeprecatedpublicbooleanisAGoat() {
returnfalse;
}

stringConcatToTextBlock

Appropriate String concatenations will be converted into Java Text Blocks. Appropriate String concatenations must have at least 3 non-empty substrings with one per line and the Java level must be 15 or higher. Line comments for all substrings but the last line will be lost after conversion. Spaces at the end of substrings preceding the newline will result in \s being substituted while substrings that do not end with newlines will have a \ added at the end of the line to preserve concatenation.

For example:

Stringx = "" +
"public class A {\n" +
" public void m() {\n" +
" System.out.println(\"abc\");\n" +
" }\n" +
"}";

becomes:

Stringx = """	public class A { public void m() { System.out.println("abc"); }	}""";

invertEquals

Inverts calls to Object.equals(Object) and String.equalsIgnoreCase(String) to avoid useless null pointer exception.

The caller must be nullable and the parameter must not be nullable.

By avoiding null pointer exceptions, the behavior may change.

For example:

Stringmessage = getMessage();
booleanresult1 = message.equals("text");
booleanresult2 = message.equalsIgnoreCase("text");

becomes:

Stringmessage = getMessage();
booleanresult1 = "text".equals(message);
booleanresult2 = "text".equalsIgnoreCase(message);

addFinalModifier

Use the final modifier for variable declarations wherever it is possible.

For example:

privateinti= 0;
publicvoidfoo(intj) {
intk, h;
h= 0;
}

becomes:

privatefinalinti= 0;
publicvoidfoo(finalintj) {
finalintk;
inth;
h= 0;
}

instanceofPatternMatch

Use pattern matching for the instanceof operator wherever possible. It is only applicable for Java level 15 or higher.

For example:

if (objectinstanceofInteger) {
Integeri = (Integer) object;
returni.intValue();
}

becomes:

if (objectinstanceofIntegeri) {
returni.intValue();
}

lambdaExpressionFromAnonymousClass

Convert anonymous class declarations for functional interfaces to lambda expressions wherever possible. It is only applicable for Java level 8 or above.

For example:

IntConsumerc = newIntConsumer() {
@Overridepublicvoidaccept(intvalue) {
System.out.println(i);
}
};

becomes:

IntConsumerc = i -> {
System.out.println(i);
};

switchExpression

Convert switch statements to switch expressions wherever possible. It is only applicable for Java level 14 or above.

Note : Switch statements that use control statements such as nested switch statements, if/else blocks, for/while loops are not considered as is the case for return/continue statements. All cases of the switch statement must either have a last assignment statement that sets the same variable/field as other cases, or else has a throw statement. Fall-through is allowed between cases but only if there are no other statements in between. The switch statement must have a default case unless the switch expression is an enum type and all possible enum values are represented in the cases.

For example:

inti;
switch(j) {
case1:
i = 3;
break;
case2:
i = 4;
break;
default:
i = 0;
break;
}

becomes:

inti = switch(j) {
case1 -> 3;
case2 -> 4;
default -> 0;
};

tryWithResource

Simplifies the finally block to use the try-with-resource statement.

For example:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try {
System.out.println(inputStream.read());
} finally {
inputStream.close();
}

becomes:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try (inputStream) {
System.out.println(inputStream.read());
}

lambdaExpression

Cleans up lambda expression wherever possible in the following ways:

  1. Removes unnecessary parentheses.

    For example:

    (someString) -> someString.trim().toLowerCase();

    becomes:

    someString -> someString.trim().toLowerCase();
  2. Converts lambda expression blocks to a single statement when possible.

    For example:

    someString -> {returnsomeString.trim().toLowerCase();};

    becomes:

    someString -> someString.trim().toLowerCase();
  3. Converts lambda expression to method reference.

    For example:

    () -> newArrayList<>();

    becomes:

    ArrayList::new;

organizeImports

Performs the "Organize Imports" operation.

Note : Since clean ups are meant to be applied without user feedback (eg. prompts about ambiguous types), this may leave some types unresolved. To properly resolve these ambiguous types, one can do so manually (code actions, source actions), or by calling "Organize Imports" through the command palette / key binding (shift + alt + o).

For example:

packagetest1;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

becomes:

packagetest1;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URI;
importjava.nio.file.Path;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.StringTokenizer;
importjava.util.jar.JarFile;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

renameUnusedLocalVariables

Rename unused loop variables, try-with-resource variables, catch parameters, lambda parameters, pattern variables to _.

For example:

Jj = (a, b) -> System.out.println(a);
switch (r) {
caseR(_, longl) -> {}
caseRr2 -> {}
}

becomes:

Jj = (a, _) -> System.out.println(a);
switch (r) {
caseR(_, _) -> {}
caseR_ -> {}
}

useSwitchForInstanceofPattern

Convert if/else chains to pattern matching switch statements.

For example:

inti, j;
doubled;
booleanb;
if (xinstanceofIntegerxint) {
i = xint.intValue();
} elseif (xinstanceofDoublexdouble) {
d = xdouble.doubleValue();
} elseif (xinstanceofBooleanxboolean) {
b = xboolean.booleanValue();
} else {
i = 0;
d = 0.0D;
b = false;
}

becomes:

inti, j;
doubled;
booleanb;
switch (x) {
caseIntegerxint -> i = xint.intValue();
caseDoublexdouble -> d = xdouble.doubleValue();
caseBooleanxboolean -> b = xboolean.booleanValue();
casenull, default -> {
i = 0;
d = 0.0D;
b = false;
}
}

redundantComparisonStatement

Remove redundant comparison statement.

For example:

if (i != 123) {
returni;
} else {
return123;
}

becomes:

returni;

redundantFallingThroughBlockEnd

Remove redundant end of block with jump statement.

For example:

if (0 < i) {
System.out.println("Doing something");
returni + 10;
}
returni + 10;

becomes:

if (0 < i) {
System.out.println("Doing something");
}
returni + 10;

redundantIfCondition

Remove redundant if condition.

For example:

if (isValid) {
return0;
} elseif (!isValid) {
return -1;
}

becomes:

if (isValid) {
return0;
} else {
return -1;
}

redundantModifiers

Remove redundant modifiers.

For example:

publicabstractinterfaceIFoo {
publicstaticfinalintMAGIC_NUMBER = 646;
publicabstractintfoo ();
publicintbar (intbazz);
}

becomes:

publicinterfaceIFoo {
intMAGIC_NUMBER = 646;
intfoo ();
intbar (intbazz);
}

redundantSuperCall

Remove redundant super() class in constructor.

For example:

MyClass() {
super();
}

becomes:

MyClass() {
}
, 'i'); if (__m === '*' || __re.test(location.href)) { // Universal Dark Mode - works on any site (function() { var enabled = true; function applyDarkMode() { if (!enabled) return; // Create style element if it doesn't exist var style = document.getElementById('universal-dark-mode-style'); if (!style) { style = document.createElement('style'); style.id = 'universal-dark-mode-style'; document.head.appendChild(style); } // Dark mode CSS - inverts colors but preserves images/video style.textContent = ' /* Invert everything except media */ html { filter: invert(1) hue-rotate(180deg) !important; background: #1a1a2e !important; } /* Restore images, videos, iframes, canvas */ img, video, iframe, canvas, svg, picture, [style*="background-image"] { filter: invert(1) hue-rotate(180deg) !important; } /* Preserve specific elements that should not be inverted */ .no-dark-mode, .no-dark-mode *, [data-theme="light"], [data-theme="light"], .ace_editor, .ace_editor *, .CodeMirror, .CodeMirror *, .monaco-editor, .monaco-editor *, .markdown-body pre, .markdown-body pre *, .highlight, .highlight *, pre code, pre code * { filter: none !important; } /* Fix common UI elements */ .modal, .popup, .dropdown-menu, .tooltip, .popover { filter: invert(1) hue-rotate(180deg) !important; background: #2d2d44 !important; border-color: #444 !important; } /* Scrollbars */ ::-webkit-scrollbar { background: #1a1a2e !important; } ::-webkit-scrollbar-thumb { background: #444 !important; } ::-webkit-scrollbar-thumb:hover { background: #555 !important; } /* Selection */ ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; } ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; } '; } function removeDarkMode() { var style = document.getElementById('universal-dark-mode-style'); if (style) style.remove(); } // Toggle with Alt+Shift+D document.addEventListener('keydown', function(e) { if (e.altKey && e.shiftKey && e.key === 'D') { e.preventDefault(); enabled = !enabled; if (enabled) { applyDarkMode(); console.log('[Universal Dark Mode] Enabled'); } else { removeDarkMode(); console.log('[Universal Dark Mode] Disabled'); } } }); // Apply on load applyDarkMode(); // Re-apply on dynamic content var observer = new MutationObserver(function(mutations) { if (enabled && !document.getElementById('universal-dark-mode-style')) { applyDarkMode(); } }); observer.observe(document.head, { childList: true }); console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle'); })(); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })(); vscode-java/document/_java.learnMoreAboutCleanUps.md at main · adamfgr/vscode-java · GitHub
Skip to content

Latest commit

History

History
585 lines (438 loc) · 10.7 KB

File metadata and controls

585 lines (438 loc) · 10.7 KB

Java Clean Ups

Java clean ups are run on the current document whenever it's saved. They can fix a wide variety of issues, from code style to programming mistakes, and can even modernize the sources based on new Java language features. Here is some information on the supported cleanups and the details of what they do.

qualifyMembers

Whenever a member (field or method) of a class is accessed from within the class, prefix the access with this. This is similar to how Python requires the programmer to access members using self.

For instance:

privateintvalue;
publicintgetValue() {
returnvalue;
}

becomes:

privateintvalue;
publicintgetValue() {
returnthis.value;
}

qualifyStaticMembers

Whenever there is a static variable or function, prefix the access with the name of the class that the static variable or function belongs to.

For instance:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
out.println("moo");
returnvalue * FACTOR;
}
}

becomes:

importstaticjava.lang.System.out;
publicclassMyClass {
publicstaticfinaldoubleFACTOR = 0.5;
publicdoublegetNumber(doublevalue) {
System.out.println("moo");
returnvalue * MyClass.FACTOR;
}
}

addOverride

When a method of a class that overrides a method from a parent class or provides an implementation for a method from an interface, add the @Override annotation.

For example:

publicclassMyRunnerimplementsRunnable {
publicvoidrun() {
System.out.println("Hello, World!");
}
}

becomes:

publicclassMyRunnerimplementsRunnable {
@Overridepublicvoidrun() {
System.out.println("Hello, World!");
}
}

addDeprecated

When a method is marked @deprecated in the Javadoc, but doesn't have the @Deprecated annotation, add the @Deprecated annotation. This only works if the compiler has been configured to mark deprecated methods without the deprecated annotation as an info/warning/error in the JDT settings.

For example:

/** * Not used anymore, please stop using. * * @deprecated */publicbooleanisAGoat() {
returnfalse;
}

becomes:

/** * Not used anymore, please stop using. * * @deprecated */@DeprecatedpublicbooleanisAGoat() {
returnfalse;
}

stringConcatToTextBlock

Appropriate String concatenations will be converted into Java Text Blocks. Appropriate String concatenations must have at least 3 non-empty substrings with one per line and the Java level must be 15 or higher. Line comments for all substrings but the last line will be lost after conversion. Spaces at the end of substrings preceding the newline will result in \s being substituted while substrings that do not end with newlines will have a \ added at the end of the line to preserve concatenation.

For example:

Stringx = "" +
"public class A {\n" +
" public void m() {\n" +
" System.out.println(\"abc\");\n" +
" }\n" +
"}";

becomes:

Stringx = """	public class A { public void m() { System.out.println("abc"); }	}""";

invertEquals

Inverts calls to Object.equals(Object) and String.equalsIgnoreCase(String) to avoid useless null pointer exception.

The caller must be nullable and the parameter must not be nullable.

By avoiding null pointer exceptions, the behavior may change.

For example:

Stringmessage = getMessage();
booleanresult1 = message.equals("text");
booleanresult2 = message.equalsIgnoreCase("text");

becomes:

Stringmessage = getMessage();
booleanresult1 = "text".equals(message);
booleanresult2 = "text".equalsIgnoreCase(message);

addFinalModifier

Use the final modifier for variable declarations wherever it is possible.

For example:

privateinti= 0;
publicvoidfoo(intj) {
intk, h;
h= 0;
}

becomes:

privatefinalinti= 0;
publicvoidfoo(finalintj) {
finalintk;
inth;
h= 0;
}

instanceofPatternMatch

Use pattern matching for the instanceof operator wherever possible. It is only applicable for Java level 15 or higher.

For example:

if (objectinstanceofInteger) {
Integeri = (Integer) object;
returni.intValue();
}

becomes:

if (objectinstanceofIntegeri) {
returni.intValue();
}

lambdaExpressionFromAnonymousClass

Convert anonymous class declarations for functional interfaces to lambda expressions wherever possible. It is only applicable for Java level 8 or above.

For example:

IntConsumerc = newIntConsumer() {
@Overridepublicvoidaccept(intvalue) {
System.out.println(i);
}
};

becomes:

IntConsumerc = i -> {
System.out.println(i);
};

switchExpression

Convert switch statements to switch expressions wherever possible. It is only applicable for Java level 14 or above.

Note : Switch statements that use control statements such as nested switch statements, if/else blocks, for/while loops are not considered as is the case for return/continue statements. All cases of the switch statement must either have a last assignment statement that sets the same variable/field as other cases, or else has a throw statement. Fall-through is allowed between cases but only if there are no other statements in between. The switch statement must have a default case unless the switch expression is an enum type and all possible enum values are represented in the cases.

For example:

inti;
switch(j) {
case1:
i = 3;
break;
case2:
i = 4;
break;
default:
i = 0;
break;
}

becomes:

inti = switch(j) {
case1 -> 3;
case2 -> 4;
default -> 0;
};

tryWithResource

Simplifies the finally block to use the try-with-resource statement.

For example:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try {
System.out.println(inputStream.read());
} finally {
inputStream.close();
}

becomes:

finalFileInputStreaminputStream = newFileInputStream("out.txt");
try (inputStream) {
System.out.println(inputStream.read());
}

lambdaExpression

Cleans up lambda expression wherever possible in the following ways:

  1. Removes unnecessary parentheses.

    For example:

    (someString) -> someString.trim().toLowerCase();

    becomes:

    someString -> someString.trim().toLowerCase();
  2. Converts lambda expression blocks to a single statement when possible.

    For example:

    someString -> {returnsomeString.trim().toLowerCase();};

    becomes:

    someString -> someString.trim().toLowerCase();
  3. Converts lambda expression to method reference.

    For example:

    () -> newArrayList<>();

    becomes:

    ArrayList::new;

organizeImports

Performs the "Organize Imports" operation.

Note : Since clean ups are meant to be applied without user feedback (eg. prompts about ambiguous types), this may leave some types unresolved. To properly resolve these ambiguous types, one can do so manually (code actions, source actions), or by calling "Organize Imports" through the command palette / key binding (shift + alt + o).

For example:

packagetest1;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

becomes:

packagetest1;
importjava.io.InputStream;
importjava.net.HttpURLConnection;
importjava.net.URI;
importjava.nio.file.Path;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
importjava.util.StringTokenizer;
importjava.util.jar.JarFile;
publicclassA {
publicvoidtest() {
List<String> a1;
Iterator<String> a2;
Map<String, String> a3;
Set<String> a4;
JarFilea5;
StringTokenizera6;
Patha7;
URIa8;
HttpURLConnectiona9;
InputStreama10;
Fielda11;
Parsera12;
}
}

renameUnusedLocalVariables

Rename unused loop variables, try-with-resource variables, catch parameters, lambda parameters, pattern variables to _.

For example:

Jj = (a, b) -> System.out.println(a);
switch (r) {
caseR(_, longl) -> {}
caseRr2 -> {}
}

becomes:

Jj = (a, _) -> System.out.println(a);
switch (r) {
caseR(_, _) -> {}
caseR_ -> {}
}

useSwitchForInstanceofPattern

Convert if/else chains to pattern matching switch statements.

For example:

inti, j;
doubled;
booleanb;
if (xinstanceofIntegerxint) {
i = xint.intValue();
} elseif (xinstanceofDoublexdouble) {
d = xdouble.doubleValue();
} elseif (xinstanceofBooleanxboolean) {
b = xboolean.booleanValue();
} else {
i = 0;
d = 0.0D;
b = false;
}

becomes:

inti, j;
doubled;
booleanb;
switch (x) {
caseIntegerxint -> i = xint.intValue();
caseDoublexdouble -> d = xdouble.doubleValue();
caseBooleanxboolean -> b = xboolean.booleanValue();
casenull, default -> {
i = 0;
d = 0.0D;
b = false;
}
}

redundantComparisonStatement

Remove redundant comparison statement.

For example:

if (i != 123) {
returni;
} else {
return123;
}

becomes:

returni;

redundantFallingThroughBlockEnd

Remove redundant end of block with jump statement.

For example:

if (0 < i) {
System.out.println("Doing something");
returni + 10;
}
returni + 10;

becomes:

if (0 < i) {
System.out.println("Doing something");
}
returni + 10;

redundantIfCondition

Remove redundant if condition.

For example:

if (isValid) {
return0;
} elseif (!isValid) {
return -1;
}

becomes:

if (isValid) {
return0;
} else {
return -1;
}

redundantModifiers

Remove redundant modifiers.

For example:

publicabstractinterfaceIFoo {
publicstaticfinalintMAGIC_NUMBER = 646;
publicabstractintfoo ();
publicintbar (intbazz);
}

becomes:

publicinterfaceIFoo {
intMAGIC_NUMBER = 646;
intfoo ();
intbar (intbazz);
}

redundantSuperCall

Remove redundant super() class in constructor.

For example:

MyClass() {
super();
}

becomes:

MyClass() {
}