The Sclass

String in Java is closed for modification. This is annoying because so many things *are* Strings in Java that I would like to have additional functionality for. (Why I like JavaScript!)

Since strings are closed for modification, one solution is to provide the extra behaviour by using a collection of static methods (which, for brevity, are collected into the class S, as in

    if (S.isEmpty(someString)) doSomething();

Note that this is an early implementation of a class that has been developed several times. The functionality is sparse, and is intended as an example for exposition later on how Java naming conventions violate readability in some situations. Renaming this class to Stringx, for instance, makes it much less pretty to work with.

    if (Stringx.isEmpty(someString)) doSomething(); 

just doesn't work for me. I'm trying to *minimize* the class name and promote the idea that it is basically a free function. Believe me, you wouldn't see anything like a set of static methods in my code if I ran the String class zoo.

package util;

public class S {

	public static String first(String s) {
		if (isEmpty(s)) return "";
		return s.substring(0, 1);
	}

private static boolean isEmpty(String s) { return s == null || s.trim().length() == 0; }

public static String nDigits(int n, int num) { StringBuffer result = new StringBuffer(String.valueOf(num)); if (result.length() > n) throw new RuntimeException("too many digits"); result.insert(0, space(n - result.length())); return result.toString(); }

private static final String SPACE = " "; public static String space(int len) { if (len > SPACE.length()) throw new RuntimeException("not enough space"); return SPACE.substring(0, len); }

public static String repeat(int n, String piece) { StringBuffer buf = new StringBuffer(piece); while (n-- > 0) buf.append(piece); return buf.toString(); } public static String twoDigits(int i) { return nDigits(2, i); }

}
CategoryJava

EditText of this page (last edited January 2, 2006) or FindPage with title or text search