Tuesday, December 5, 2006

Just Try It

I love answering programming questions. It lets me feel like a grizzled veteran sharing my arcane knowledge with those eager to learn. (Yes, I'm delusional.) If I don't know the answer, I enjoy finding out.

Most people don't know all the arcane language rules of every language they use. As I get older, I'm less inclined to memorize a language spec or an API. For example, yesterday I wondered if the Java 5 enhanced for loop calls the collection expression once or every time through the loop. I searched for the answer online, and couldn't find one. After a few minutes, I realized that it would be faster to write a small program to determine the answer. Within two minutes, I knew. (I'm saving the answer and the code for another blog post.)

If you have a question about a language rule or the use of a library, there is more than one way to find the answer: read the documentation, ask somebody else, or try it. If at all possible, Just Try It™—write a small program that answers your question. Even better, if your language has a REPL or even accepts input from stdin, then type a few lines of code interactively.

Ruby comes with irb, the Interactive Ruby Browser. Every Lisp has a REPL. Smalltalk has the Workspace. Shell languages have the shell.

When you Just Try It, you gain the immediate satisfaction of knowing the answer. You also use a different part of your brain then when you read the answer online; I claim you absorb the answer more thoroughly if you write a small code snippet. You might want to keep a collection of these code snippets for yourself. I have a personal Wiki (an Emacs Wiki, of course) where I store these sorts of things if they're useful enough. There are also a few snippet collection Web sites out there, such as Code Snippets.

No comments: