Why didn't Java designers create static versions of string manipulation methods in the
java.lang.String class? The following methods are what I refer to, but the question can be extended to other non-static methods in the class as well.
concat(String) substring(int, int) replace(char, char) toLowerCase() replace(CharSequence, CharSequence) toLowerCase(Locale) replaceAll(String, String) toString() replaceFirst(String, String) toUpperCase() split(String) toUpperCase(Locale) split(String, int) trim() substring(int)
Having only non-static versions of these methods forces explicit null-checking anywhere such a method has to be called. For example, simply calling
example = example.trim() would lead to NullPointerException if
String example = null. So the programmer has to do the following boilerplate null check:
if (example != null) example = example.trim(); // OR: example = (example==null) ? null : example.trim(); example = (example==null) ? null : example.substring(5);
I would imagine it would have been a lot more convenient if
String had static versions of these methods (perhaps even exclusively), which would take the input string as the first argument:
example = String.trim(example); example = String.replace(example, 'a', 'b'); example = String.substring(example, 5);
This would have led to cleaner code written by programmers which would have automatically taken care of null cases by simply returning null, rather than forcing programmers to explicitly handle null cases. The returning of null makes sense to me since manipulating a null string should result in a null string, not an error.
Why didn't Java designers think of this when they designed the
String class in Java 1 or Java 2, or even add such a functionality in a later Java version?
nullis an exceptional state and should be handled explicitly.
Maybe<T>type, I guess?
string name = employee?.personalData?.name. Just as a shortcut for all these repetitive
if (employee != null)s. Related SO question: stackoverflow.com/questions/1196031/…