Skip to content

Commit

Permalink
ignore string concatenations that must be split over multiple lines
Browse files Browse the repository at this point in the history
  • Loading branch information
Luro02 committed Apr 4, 2024
1 parent 114fd18 commit edd819b
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@
public class UseFormatString extends IntegratedCheck {
private static final int MIN_NUMBER_CONCATENATIONS = 3;
private static final int MIN_NUMBER_LITERALS = 2;
// A line is about 120 - 140 characters long. Assuming a relatively long constant name,
// there remain around 70 characters for the string value.
//
// For longer string values one will split the string into multiple lines:
//
// "This is a very long string that is split into multiple lines"
// + " to make it more readable."
//
// Those should not be flagged.
private static final int MAXIMUM_STRING_LENGTH_IN_LINE = 55;

private List<CtExpression<?>> getFormatArgs(CtBinaryOperator<?> ctBinaryOperator) {
List<CtExpression<?>> result = new ArrayList<>();
Expand Down Expand Up @@ -107,6 +117,10 @@ private String buildFormattedString(Iterable<? extends CtExpression<?>> ctExpres
args.add(ctExpression.prettyprint());
}

if (args.isEmpty() && formatString.length() >= MAXIMUM_STRING_LENGTH_IN_LINE) {
return null;
}

if (args.isEmpty() && !hasInlineNewline) {
return "\"%s\"".formatted(formatString.toString());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,4 +148,23 @@ public String toString() {

problems.assertExhausted();
}

@Test
void testLongConstant() throws LinterException, IOException {
ProblemIterator problems = this.checkIterator(StringSourceInfo.fromSourceString(
JavaVersion.JAVA_17,
"Field",
"""
public class Field {
private static final String MY_VERY_LONG_CONSTANT_STRING = "This is a very long constant string that is used in the code."
+ "It is so long that it has to be split over multiple lines."
+ "It is so long that it has to be split over multiple lines."
+ "It is so long that it has to be split over multiple lines."
+ "It is so long that it has to be split over multiple lines.";
}
"""
), PROBLEM_TYPES);

problems.assertExhausted();
}
}

0 comments on commit edd819b

Please sign in to comment.