On simple language and API design: Java vs. Python

How do you capture the latest 15 chars on a Java String? Easy!

String str = "The quick brown fox";
String last = str.substring(str.length() - 15);
System.out.println(last);

What if, for some misfortune, you read a String with less than 15 characters?

String str = "The quick";
String last = str.substring(str.length() - 15); // boom
System.out.println(last);

If you're not careful enough with the sizes of the Strings you're dealing with, you end with a StringIndexOutOfBoundsException, which is a Exception than aborts the execution of the flow of code in that thread.

The natural solution for that is creating a method as follows:

static String rightmost(String s, int amount) {
    int len = s.length();
    if (amount > len) return s;

    return s.substring(len - amount);
}
public static void main(String[] args) {
    System.out.println(rightmost("The quick brown fox", 15)); // Outputs "quick brown fox"
    System.out.println(rightmost("The quick", 15)); // Outputs "The quick"
}

The lack of a no-surprises implementation for trivial operations makes Java a language that's difficult for begginers to grok. In simple stuff like this is where a well-designed language like Python shines:

st = 'The quick brown fox'
print st[-15:] # prints 'quick brown'
st = 'The quick'
print st[-15:] # prints 'The quick'

Three points here:

  • First, Python substring manipulation is first class (by letting you grab a piece of the string simply by using the [] operator)
  • Second, it takes care of indexes that may be overflow the size of the string (think: forget bounds-checking, we're not doing C here!)
  • Third, it lets you express succinctly "grab the last 15 chars" by using the [-15:] notation, where you also could use [:-15] to say "all except the last 15 chars"

It's intuitive, it's safe, and I'm inclined to say... beautiful, too.

String subscripting in Python is just a small but tremendously useful feature of the language. Learn more about it here.

Final note: Yes, I know there is something called StringUtils inside CommonsLang that contains a safe version of the substring method, an implementation of rightmost (as right), and a myriad of other methods for String manipulation. But let's say we try hard to avoid bundling yet another library.

Comentarios

Comments powered by Disqus