Monthly Archives: May 2005

Calling all Mac developers in Washington DC / Virginia / Maryland

I want to start up a Mac developer group in the DC Area that would bring together Mac programmers, focusing on Cocoa.

I figure that there must be several of us out there, but we just don’t know each other yet. The DC area is one of the top metropolitan regions in the country and is the fastest growing outside of the Sunbelt. So it is one of the key target markets of Apple and hosts a big population of Mac users.

There’s already three Apple retail stores in the area: Tysons Corner, Clarendon and Bethesda. There is a fourth under construction at Pentagon City Mall. Tysons Corner was actually the first Apple retail store to open back in 2001.

To put this in perspective, there are currently as many stores in the area as there is in the entire state of Oregon and after Pentagon City completes, as many as in all of Washington state. Of course, California still is the leader by far. Here’s a nice map that illustrates where all the Apple stores are.

So Apple knows that they have good customers in the DC area.

Hopefully there are some good Mac programmers in the DC area as well. Let me know who you are by sending me email at cocoa at luisdelarosa.com. Also, you can join the Cocoa DC group I set up at http://groups-beta.google.com/group/cocoa-dc.

Iterating over OrderedCollections

One of the things you want to do after having an OrderedCollection (aka List or Array) is to iterate over the elements. I’ll look at the languages I’m interested in: Smalltalk, Java, Objective-C, Ruby, Python, and C#.

First off, Smalltalk. I think they got it right, by having blocks / closures as being first-class elements of the language. You can re-use blocks and each block has its own scope. Here’s how to iterate in Smalltalk:

list do: [ |item| item doSomething]

Next up, Ruby. Ruby’s next because it comes closest to Smalltalk. It too has blocks. Here’s how to iterate in Ruby:

list.each { |item| item.doSomething }

Since we just did Ruby, let’s see how Python iterates:

for item in list:
  item.doSomething()

And why not… C# iteration:

foreach (ItemClass item in list) {
  item.DoSomething();
}

I’ve saved Java and Objective-C for the last because they are a bit more complicated than the rest, at least historically.

Java, pre-Java 1.5 / 5, many programmers used typed arrays and then used a for loop to iterate:

ItemClass[] list = new ItemClass[size];
// fill in the list
for (i = 0; i 
You could have also used either an Enumerator (if using the legacy Vector) or Iterator/ListIterator if using List. Java 1.5 gives you a much cleaner way to iterate:
for (ItemClass item : list) {
  item.doSomething();
}

Finally, Objective-C has something called NSEnumerator. Apple advises programmers to iterate this way:

NSEnumerator *enumerator = [list objectEnumerator];
id item;
while (item = [enumerator nextObject]) {
    [item doSomething];
}

But many of us aren't quite happy with this way of doing things. There's no type information, since id is any object. Making a method call, assigning to an object reference, and testing a boolean all in the while test is too much in one place. Jonathan 'Wolf' Rentzsch has a great page that dissects this and he offers a nice macro that boils down to:

nsenumerate(list, ItemClass, item) {
  [item doSomething];
}

I think that while this is much better, it just doesn't seem like it is in the right order. I modified Wolf's macro a bit and renamed it to "foreach":

foreach( ItemClass, item, list )  {
  [item doSomething];
}

Note that for these macros to work, you need to set the Project Setting "C Language Dialect" to either "C99" or "GNU99".

All of these seem to be good at limiting scope and lifetime of the item variables. There are two styles in use: the block iterator and the "enhanced for" iterator. I prefer the block iterator, but it doesn't seem to be available for most languages. The "enhanced for" is the next best and with the slight modification to Wolf's nsenumerate macro, they all look very similar.

Comparison of OrderedCollections in Smalltalk, Java, Objective-C, Ruby, Python, and C#

In my last post, I compared the collections classes at a high level. Now I’m diving into the one that is most often used, the OrderedCollection.

What’s an OrderedCollection? It is the collection class in Smalltalk that supports ordering. Seems straightforward, but why use the Smalltalk name for it? Why not the more popular List or Array? Because Smalltalk and its collection classes have been around for much longer (over 25 years) than the other languages I’m comparing. All the other languages actually derive in some fashion from Smalltalk.

I haven’t done that much Python and C#, but I figured I should check them out while I am at it. For the others, I have done quite a bit and I wanted to take a step back and look at how each compares.

Here’s a table that compares the API for each language:
(Note that I’ll use “list” since it is shorter than “OrderedCollection” so it can fit nicely in this table.)

Smalltalk Java Objective-C Ruby Python C#
OrderedCollection List – ArrayList NSArray / NSMutableArray Array List IList – List
list := OrderedCollection new List<Type> list = new ArrayList<Type>() NSMutableArray *list = [NSMutableArray array]; list = Array.new or list = [] list = [] IList list = new List();
list size list.size(); [list count]; list.length len(list) list.Count()
list isEmpty list.isEmpty(); not included list.empty? ? ?
list add: item list.append(item); [list addObject: item]; list.push(item) list.append(item) list.Add(item);
list addAll: anotherList list.addAll(anotherList); [list addObjectsFromArray: anotherList]; list = list + another_list list.extend(anotherList) list.AddRange(anotherList);
list remove: item list.remove(item); [list removeObject: item]; list.delete(item) list.remove(item) list.Remove(item);
list indexOf: item list.indexOf(item); [list indexOfObject: item]; list.index?(item) list.index(item) list.IndexOf(item);
list includes: item list.contains(item); [list containsObject: item]; list.include?(item) item in list list.Contains(item);
list at: index list.get(index); [list objectAtIndex: index]; list.at(index) or list[index] list[index] list[index];

Now I’m going to argue against using Array as a name, because people tend to confuse it with C-style arrays. Most of these languages can interface with C (usually to optimize certain sections of code or to interoperate with legacy libraries) and so it is nice to not have two concepts referred to via the same name. So ideally I’d like to see Ruby change Array to List and Obj-C/Cocoa use NSList and NSMutableList. I doubt I will make this happen, however. :)

Next, more heresy: Java and C# have backwards syntax for constructors. Why don’t they just make it like every other method call and have a “new” method at the class level like every other language? (Not sure if Python’s List is actually a class.) Hmm… maybe someone can contribute this for Java 6?

Nobody seems to agree on a method name for size, count, or length. Note that Python doesn’t seem to have a method for this, rather a len() function. Also Python doesn’t have an includes: method, but an “in” language operator.

Java seems to mirror Smalltalk nicely, with a few wording changes and a C++-like syntax. I included the type-safe Java 5 syntax for the Java constructor to show how it makes life a bit safer with compile-time type safety, but also clutters the code a bit to accommodate the type. Note that this clutter is saved later when you get rid of casts.

Objective-C also mirrors Smalltalk, but seems to add “Object” everywhere, making them verbose. I wouldn’t mind if this got replaced by a more bare protocol later on.

Actually, Obj-C has a language feature called “categories”, which lets you extend an existing class without creating a subclass. So does Ruby and possibly Python. Java does not let you do this. Not sure of C#. I think I will try and see if creating and using a new Obj-C category and Ruby mix-in that lets me use the Smalltalk-canonical method names will be easier, since I will only have to remember one set of method names.

Note also that Objective-C has to wrap method calls in square brackets.

Also Objective-C (actually Cocoa’s Foundation Kit) has both an immutable and a mutable version. The immutable version gives you thread-safety and is faster. I addressed this in the earlier post about collections. Note that Java’s ArrayList is not thread-safe by default.

Ruby has an interesting convention of using ? at the end of its method names instead of using “is” and camel-casing. Note that camel-casing is discouraged in Ruby. Instead, the preferred Ruby convention is a_long_method_name instead of aLongMethodName. It also seems to be derived from Python as well as Smalltalk, but is more object-oriented. While it has the [] operator like Python, it uses methods instead of len() and the keyword in.

C# looks just like Java. Note that C# 2.0 has Generics support, like Java 5. The only thing that is odd is that it uses a different casing model, with the first letter of the method name uppercased.

Next: iterating over OrderedCollections.

Comparison of Collections in Smalltalk, Java, Objective-C, Ruby, Python, and C#

Why look at collection classes? Well, after reading a bit about the language syntax and writing “Hello World”, I think the next thing you should learn about a language/framework is its Collections classes. Its one of the things that makes programming in a higher than C level language more powerful. Its also one of the most basic. You’ll find that the other parts of your chosen framework whether it is Cocoa, Eclipse, Rails, or whatever, uses these collection classes heavily.

Also, I’ve been writing code in these different languages, so I’m using this to help me get straight what the APIs are like for each collection class. Hopefully this will help you out if you’re transitioning from one language to another.

Let’s see what each language has to offer in terms of the 3 basics: OrderedCollection, Dictionary, and Set. Dictionary holds key/value pairs and Set holds unordered, unindexed, unique objects. I’m using the Smalltalk class names as the canonical names, since it is the GrandDaddy of all object-oriented languages.

Smalltalk Java Objective-C Ruby Python C#
OrderedCollection List – ArrayList NSArray / NSMutableArray Array List IList – List
Dictionary Map – HashMap NSDictionary / NSMutableDictionary Hash Dictionary IDictionary – Dictionary
Set Set – HashSet NSSet / NSMutableSet Set [1] ? ?

Some brief thoughts on the language differences:

Objective-C / Cocoa, though more specifically the Foundation Kit, which is the non-UI related frameworks, offers immutable and mutable versions of each collection. This is unique and seems like a premature optimization at first. However, if you’ve ever read Josh Bloch’s Effective Java, you’ll realize that he recommends using immutable objects whenever possible, to reduce errors and ensure type-safety.

Also, all the Foundation Kit classes start with “NS”, which stands for NeXTStep. This is a workaround for not having namespaces as part of the language.

Java has a strict separation of interface and implementation. This is nice in one sense, but cumbersome in another. Its too bad you can’t just say new List() and have a factory that you configure in your application that tells you when to instantiate which implementation.

Also, Java has the largest and thus hardest to memorize collections API. There are multiple implementations of each interface. I included the ones that should be used by default for most cases. There are old versions of APIs (Vector and Hashtable) which tend to confuse veterans who used to use them and beginners alike. There are typesafe (Java 5/1.5 only) and non-typesafe versions (which involve casting.) Before Java 1.5, many programmers would just use typed arrays to get type safety. There’s also immutable versions of collections, but these are not protected via API, instead they throw UnsupportedOperationExceptions at run-time.

Java and C# have type-safe at compile-time collections. This is both good and bad, but in my opinion, it is rarely a problem in practice with the dynamically-typed languages. In general, C# seems to behave similarly to Java.

[1] UPDATE: Set available for Ruby as part of the Standard Library. Thanks to John Labovitz for pointing this out.

How to find out what you like to do

When I was in 5th grade, I took a test in school that would tell me what career I would be best suited for. My top two results were Radio DJ and Engineer. I’ve never been a DJ, but I do like music. I don’t consider myself an engineer, but a programmer. I guess that was close enough. In retrospect that seems like a strange way to do this, especially when you’re so young. What if my top two results were Janitor and Astronaut?

I think I’ve stumbled upon a good way to find out what you like to do, much better than some multiple choice test that is based off of some statistical sampling (even though that sounds good in theory.)

What’s this way? Three words:

Go on vacation.

You can look at how someone spends his free time and figure out from there what he likes. However, people’s schedules can be filled to the brim with activities that there isn’t much free time left over. So the observations can be skewed.

However, when you go on vacation, you basically take all this free time and package it together into one nice big chunk. You also free yourself up from some of the daily chores that were taking up some of your valuable free time (like feeding the dog or doing laundry.) In essence, you are doing what you would do if you “won a million dollars.” Well, except you’ve got a limited budget and you only get to do it for a week or two at a time (at least in the US; Europeans are probably chuckling right now.)

So next time you’re on vacation, take along a little notebook and write down what you’ve done each day at the end of the day. You may be surprised at what you actually like to do.

Me? Well, I’m writing this blog entry from vacation, so I obviously like doing that, along with reading blogs. I’ve been spending time with my wife, playing with my kids, seeing some sights, and taking pictures. I think those are universal. What’s different is that I also like designing and writing software… on vacation. I’m not working on work stuff, but rather on apps that satisfy my personal needs (and hopefully others as well). Along the way I’m learning new frameworks and techniques that I’ve been interested in like Core Data and Cocoa Bindings. I also like reading books (currently about Cocoa and about business.) And for some reason, I like to watch the NBA Playoffs.

Eclipse 3.1M7 released

Like clockwork, the Eclipse team has released Eclipse 3.1 M7, which is the last milestone build before the official Eclipse 3.1 (which should come out in late June.)

eclipse 3.1 logo

There’s a few new features, but I think the main focus in this release was performance improvements and stability. A big improvement was with the Java Dev Tools (JDT):

“As an example, launching a workspace containing all Eclipse SDK sources used to take close to 2 minutes in 3.1 M6. It now takes under 10 seconds.”

Superb! For more good stuff, read the New and Noteworthy for 3.1M7. Note that there is a new splash screen (shown to the right) that they want comments on.

This release has some nice improvements specifically for Eclipse on Mac users. It is the first Eclipse release that I consider “Tiger-friendly” or more specifically, “Spotlight-friendly.” That is because the default key binding for Content Assist on the Mac is now Control-Space, avoiding the conflict with Spotlight which uses Command-Space. I blogged about that earlier in “Everyone Loves Command-Space“.

Also for Eclipse-Mac users, mostly thanks to Andre, the default memory size has been increased to be the same as the other platforms: 40M minimum heap and 256M maximum heap. All the VM settings have been moved to eclipse.ini, which is located in eclipse/Eclipse.app/Contents/MacOS. So do not touch Info.plist if you do not have to from now on. Instead, edit eclipse.ini. In fact, there is a new warning in Info.plist that reads:

            &lt!-- WARNING:
                If you try to add a single VM argument (-vmargs) here,
                *all* vmargs specified in eclipse.ini will be ignored.
                We recommend to add all arguments in eclipse.ini
             --&gt

You can download Eclipse 3.1 M7 here.

Everybody loves Command-Space

I’m running Tiger full-time now and its great. Spotlight is one of the best new features in it and I’m looking forward to more and more programs becoming Spotlight enabled (like VoodooPad). I’ve got an app I’ve been working on that has searching in it that I’ll work on getting Spotlight-enabled by the time I go to WWDC. I’ll probably release it in beta soon after that.

Spotlight can launch apps (though don’t launch Eclipse with it yet), find documents, find folders, find emails, find calendar entries, find images, find music, find your code, etc. I know that there are other third party apps for searching your computer, but none that are tightly integrated into the OS and user experience.

The only problem I had with Spotlight was that it uses Command-Space. For most Mac users, that probably won’t be a problem. But for me, I already had two apps that wanted to use that same key combo: Eclipse (on Mac OS X) and Quicksilver. Eclipse uses it for Content Assist and Quicksilver to bring up the interface.

In Panther, I said Eclipse wins. So I re-mapped Quicksilver to use Command-Esc.

But in Tiger, I’m trying to stick with Control-Space for Spotlight. I first added Option-Space for Content Assist in Eclipse, but that doesn’t work. I ended up assigning Control-Space to Eclipse for Content Assist (tip: Eclipse 3.1M5 and up has its own Spotlight-like search for preferences, so just type “keys” in the search field to find the place to add this) and Command-Esc to Quicksilver. This seems to be working well for me now, though my muscle memory still wants to use Command-Space for Content Assist. I remapped Caps Lock to Control to compensate (remapping modifier keys is another new feature in Tiger.)

Washington Wizards make it to the 2nd round!

Washington Wizards logoFinally, after a long drought of 23 years, the Washington Wizards win a playoff series. They beat the Chicago Bulls 4 games to 2 tonight at home in the MCI Center, located in downtown Washington DC (right near Chinatown actually). It was exciting, with big point swings and big plays, including a Chicago player getting the ball bounced off his back, leading to a nice breakaway dunk by Washington’s Jared Jeffries.

I was bouncing off the walls when they won and gave my dog an extra treat. It has been a long time since DC denizens have had some good basketball to get excited about. Even James Carville and Tim Russert were ecstatic at courtside. LA may have the movie stars, but we’ve got the political consultants!

BTW, I thought it was fitting that Tyson Chandler went for a 2 pointer as time ran out even though Washington was up by 3. He committed a really rough flagrant foul on Larry Hughes earlier in the game. Another time, when Jeffries got poked in the eye, he pulled away one of his teammates who was trying to comfort Jeffries.

What is amazing is the fact that the Wizards are now only the ninth NBA team to win a playoff series after starting off 0-2. I don’t know how they’ll do against Miami, but there will be at least 4 more playoff games for the Wiz. And so us Washington fans will get at least a few more times to watch and root for our team.

Nerds don’t have to be unpopular

Graham lent me this great book Hackers and Painters which I just finished reading. I highly recommend it to anyone who loves to program. Or if you want to understand how programmers think. It is interesting that Paul Graham chose to use the word “Hacker”, which has bad connotations nowadays, but back in the old days it meant that you were a great programmer. The kind of programmer they describe in Peopleware: Productive Projects and Teams (another classic book on programmers) that programs 10x the average programmer. Also known as GrandMasterProgrammer.

The first chapter was completely unexpected. This book is published by O’Reilly and it is one of those ones without an animal on the cover, which means folks are writing about stuff at a high level. But this was unlike any chapter of any O’Reilly book I’ve ever read. It was titled “Why Nerds are Unpopular.” In it, he describes the typical experience of nerds in the US: they’re unpopular, they get picked on and have a generally miserable experience in high school.

But I don’t think it has to be that way.
Continue reading