Ported Swing app to Cocoa-Java

March 20, 2005

Remember that Swing app I had to do for my Software Engineering course recently? Today I ported it to Cocoa. At first I thought I would port it to Objective-C at the same time, but that would have been too much work, there was so much code. So I decided to (gasp!) keep it in Java.

Turns out my line count was a little bit off... I accidentally submitted the assignment with one .java file that I refactored out of my implementation but forgot to delete, so instead of 6364 lines of code in 37 files it was 6291 lines in 36 files.

The Cocoa version has only 26 .java files, with a total of 4027 lines of code... 16 (5*3 + 1) files removed containing 3032 lines of code, 6 (5 + 1) files added containing 768 lines of code.

The six files added included 5 window controllers and one simple class that initialized the domain model and provided the window controllers access to it. All 6 classes were instanciated and connected to each other and view components as necessary in the .nib file.

Actually, one of the window controllers is completely unnecessary in the new design, but I created it anyway. That essentially empty 10-line subclass of NSWindowController could be removed, making it only 5 files added containing 758 lines of code.

The 16 files removed included 5 JFrame subclasses, 5 POJO window controllers for those JFrames, and 5 interfaces that the window controllers implemented. Each JFrame held a reference to its window controller typed as the corresponding interface. The 16th file was the main class, "Application.java" file that set up the domain objects, set up the first window controller, and told it to show its window in its 'public static void main(String[] args)' method. Startup is handled by Cocoa, so the new class that replaced this one just set up the domain objects.

If one wanted to be picky they could say the Cocoa app added two other files, "main.m" (14 lines of code) and "CocoaApplication_Prefix.h" (7 lines of code), but I'm not quite that picky.

So the Swing application was 3032 lines of code in 16 files, vs. 758 lines in 5 files for the Cocoa-Java version.

Bottom line:

The Swing version required 3.2 times more source files and 4.0 times more lines of code. Of course, these figures include comment lines, but the degree of commenting is actually very consistent between both versions, so I don't think it's a factor here.

Too bad Cocoa doesn't run on Windows or Linux, or, too bad Mac OS X doesn't run on PCs.