Skip to content

Instantly share code, notes, and snippets.

@darekmydlarz
Created November 28, 2017 07:10
Show Gist options
  • Save darekmydlarz/1bfd98dfb7e84eb73673f1786b758679 to your computer and use it in GitHub Desktop.
Save darekmydlarz/1bfd98dfb7e84eb73673f1786b758679 to your computer and use it in GitHub Desktop.
package com.getbase.services.reach.api.dtos.request;
/**
* Put quotes around the given String if necessary.
* <p>
* If the argument doesn't include spaces or quotes, return it as is. If it
* contains double quotes, use single quotes - else surround the argument by
* double quotes.
* </p>
* <p>
* Copied from Apache Commons Exec: http://commons.apache.org/proper/commons-exec/
*/
class QuotedString {
private static final String SINGLE_QUOTE = "\'";
private static final String DOUBLE_QUOTE = "\"";
private final String argument;
public QuotedString(String argument) {
this.argument = argument;
}
public String toString() {
String cleanedArgument = argument.trim();
// strip the quotes from both ends
while (cleanedArgument.startsWith(SINGLE_QUOTE) || cleanedArgument.startsWith(DOUBLE_QUOTE)) {
cleanedArgument = cleanedArgument.substring(1);
}
while (cleanedArgument.endsWith(SINGLE_QUOTE) || cleanedArgument.endsWith(DOUBLE_QUOTE)) {
cleanedArgument = cleanedArgument.substring(0, cleanedArgument.length() - 1);
}
final StringBuilder buf = new StringBuilder();
if (cleanedArgument.contains(DOUBLE_QUOTE)) {
if (cleanedArgument.contains(SINGLE_QUOTE)) {
throw new IllegalArgumentException("Can't handle single and double quotes in same argument");
}
return buf.append(SINGLE_QUOTE).append(cleanedArgument).append(
SINGLE_QUOTE).toString();
} else if (cleanedArgument.contains(SINGLE_QUOTE) || cleanedArgument.contains(" ")) {
return buf.append(DOUBLE_QUOTE).append(cleanedArgument).append(
DOUBLE_QUOTE).toString();
} else {
return cleanedArgument;
}
}
}
@darekmydlarz
Copy link
Author

darekmydlarz commented Nov 28, 2017

The quoting part is taken from Apache Commons Exec.
In the lib, you use this piece of code in a procedural way, e.g:

String quoted = StringUtils.encodeArgument(argument);

In my OOP version you just compose objects, e.g.:

QuotedString quoted = new QuotedString(argument)

Come up with benefits you gain:

  1. object code is lazy - it doesn't perform heavy calculation if not needed
  2. it is easy to test
  3. it is small, so easy to maintain in the future
  4. it is easy to use in collections - you can wrap N items in collections, but in the end use just few of them; instead of calling transofrmations on all objects, you apply them on part of it - more performant, etc.
  5. Object creation withnew is cheap in Java
  6. QuotedString is immutable - can be easily passed to multiple threads, etc.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment