If you want to configure a Java application, the standard way to do it is to use the Java Properties class. This class wraps around a simple, text-based file format (or an XML file, if you’re into that) that allows you to store key/value pairs. It helpfully inherits from the HashMap class, letting you interact with those key/value pairs using a well understood API. The file format handles all the details of encoding and managing things like multiline strings.

So you could just do that. Or, you could do what this senior dev with over a decade of experience did.



String[] reasons = reason.split("\\n");
StringBuilder builder = new StringBuilder();
for (int i = 0; i < reasons.length; i++) {
  if (i == reasons.length - 1) {
    builder.append(reasons[i]);
  } else {
    builder.append(reasons[i] );
    builder.append(System.lineSeparator());
  }
}


String formattedReason = builder.toString();

This code handles multiline strings. The config file this developer invented simply stores its values on a single line, so to imitate multiline strings, it stores them with \n in the file (as opposed to n to represent a newline). So this code splits on \n (which, of course, needs to be escaped, to \\n), and then iterates across that split, joining the lines with a System.lineSeparator().

The only good idea in this entire block is the use of System.lineSeparator(), and I’m honestly shocked that they used the platform independent value, and not a hard-coded n.

I suppose the comment does justify and explain the code: It seemed like a good idea, it was cheaper, and they didn’t expect to get caught.

[Advertisement] ProGet’s got you covered with security and access controls on your NuGet feeds. Learn more.

Remy Porter

Source link

You May Also Like

Just Girly Things

Tags: live, laugh, love 3018 points, 102 comments. Source link

The Reality Of Being A Mother Of Twins

“My wife, and the mother of our twins, apparently just needed a…

2024 Mean Girls Forced To Remove Joke After Lindsay Lohan Is Left “Very Hurt And Disappointed”

That was so not fetch! A controversial joke referencing Lindsay Lohan’s problematic…

HumorFeed – Bending the News Until it Breaks

Commemorating the official end of slavery, the day of (and let’s face…