In the past, I used to use Initialize-On-Demand Holder, but recently I have made a singleton with enum. Below is an example of a string utility class.
Basically, create an enum that also has the only element, ʻINSTANCE`, All you have to do now is create the public method normally. It's easy and easy.
StringUtility.java
package jp.fumokmm;
import java.util.Objects;
public enum StringUtility {
INSTANCE;
/**
* <p>Trims the specified string.
*If the specified string is null, an empty string will be returned.</p>
* @param str string to trim
* @return String after trimming
*/
public String trim(String str) {
return Objects.nonNull(str) ? str.trim() : "";
}
/**
* <p>Trims the specified character string (including double-byte spaces).
*If the specified string is null, an empty string will be returned.</p>
* @param str string to trim
* @return String after trimming
*/
public String trimFull(String str) {
if (Objects.isNull(str)) return "";
int len = str.length();
int st = 0;
char[] val = str.toCharArray();
while (st < len && (val[st] <= ' ' || val[st] == ' ')) {
st++;
}
while (st < len && (val[len - 1] <= ' ' || val[len - 1] == ' ')) {
len--;
}
return (st > 0 || len < str.length()) ? str.substring(st, len) : str;
}
}
StringUtilityTest.java
package jp.fumokmm;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import org.junit.Test;
public class StringUtilityTest {
@Test
public void testTrim() {
StringUtility util = StringUtility.INSTANCE;
assertThat(util.trim(null), is(""));
assertThat(util.trim(" "), is(""));
assertThat(util.trim(" a "), is("a"));
assertThat("Full-width space is not trimmed", util.trim(" a "), is(" a "));
}
@Test
public void testTrimFull() {
StringUtility util = StringUtility.INSTANCE;
assertThat(util.trimFull(null), is(""));
assertThat(util.trimFull(" "), is(""));
assertThat(util.trimFull(" a "), is("a"));
assertThat("Full-width space is also trimmed", util.trimFull(" a "), is("a"));
}
}
By the way, in the above test
StringUtility util = StringUtility.INSTANCE;
I use it after assigning it to a variable once like
StringUtility.INSTANCE.trim(str);
You can use it as it is. Please check the readability and use it.
that's all.
Recommended Posts