Thursday, January 18, 2007

String and StringBuffer

I have been doing quite a few interviews during the last 3 months, looking for senior C++ and Java programmers. We are looking for people who are smart and who can get things done. It is interesting to see how many people have "how to" knowledge but lack fundamental understanding about how computers work. This is especially true for people who only know Java (I recommend against hiring a senior developer who only knows one programming language, whatever this language may be).

For example, let's say you ask what is the difference between String and StringBuffer. Easy enough, they respond: String cannot be changed while StringBuffer can be.

Then I ask why they think Java is designed this way. The C++ STL has only one type for instance, called string (or wstring), and it is mutable. So why did Gosling and Steele choose to use two classes?

You would not believe the number of candidates with 10 years of experience who cannot answer this question: they look at me puzzled, not knowing what to do. And I am really trying to help them. "Just don't think about strings, what advantage can you see for immutable objects in general? In a multi-threading context for instance?" Sometimes the best answer I can get is that "it helps with performance" but without any details.

I actually don't know the details about Guy Steele's decision, but any answer like these would work:
  • Immutable objects are thread-safe by definition.
  • Strings are often used as keys in hash tables, so it is interesting to have an immutable string (otherwise you would need to copy the keys).
  • You can save memory by sharing the character array between different String instances (the String.intern() method).
Here is another example. First question: "In an operating system, what is the kernel?" (easy question). Second question: "So how does your application communicate with the kernel?" (no clue). libc/glibc, system calls, context switching are apparently very abstract concepts for the average programmer.

No comments: