Archive

Archive for the ‘Uninteresting’ Category

Impressions from my first six months of OS X development

January 3rd, 2010

Since I started my new job about 6 months ago, I’ve almost exclusively been programming in Objective-C + Cocoa for OS X (and to a minor extent iPhone). I’ve been thinking that I should summarize my first impressions of it somewhere so I’ll do it here.

The syntax

My first issue with the language was the syntax. It’s function calls look similar to the ones in LISP, even though the language is a lot closer to Java or C++. Writing function calls nested like

[[foo bar] haveFunWithStuff:stuff andMoreStuff:moreStuff];

instead of

ClassName.bar().haveFun(stuff, moreStuff);

is actually not that big of a deal. The main issue i have with it is that Objective-C methods become quite verbose, and Cocoa in particular has quite lengthy method names in it’s library.

The reason for using a somewhat weird syntax is pretty obvious though. Since Objective-C is a strict superset of C, it makes it apparent which code is “pure” C and which code isn’t. I assumed this is the reason for using the unusual string syntax @”foo bar” as well (to avoid parser collision with C style strings).

Dynamic typing

Since I’ve coded a bunch of python stuff I’m used to dynamic typing, but I don’t really think having it mixed with static typing like in Objective-C is that pretty. For an example, if you want to use the standard event bindings in Interface Builder, you might hook up one of your buttons to the message buttonDown on a controller in your application. The declaration of this method is.

- (IBAction)buttonDown:(id)sender;

This specifies that the sender can be an object of any type. Nothing can really be assumed about the sender, and any method can be called on it (however, if the actual instance doesn’t support the call an error will occur). The documentation for buttonDown can however state that sender should implement an informal protocol). Essentially this means that instead of forcing a formal protocol (like an Interface in Java), it assumes that the instance supports one or more methods. If it doesn’t then the application fails during runtime.

Cocoa also has support form formal protocols, which works like interfaces in Java. These look like

- doStuff:(id <MyProtocol>)foo;

and implicitly forces foo to implement the methods in MyProtocol. Dynamic typing IS useful, but I don’t really like having the protocols declared by the documentation and not the code.

Memory Management

Up until OS X 10.5, Objective-C applications for OS X didn’t support garbage collection. This meant that only manual memory management was supported, and this is handled through manual reference counting.

Essentially, every time an object instance foo becomes dependent on another object bar, foo is responsible for retaining bar. This is done by increasing its reference count by one like:

// Inside Foo.m
- setBar:(BarClass*)bar {
  myBar = [bar retain];
}

Foo is also responsible for decreasing the reference count of bar when it’s done using it. This means that writing a setter for an object property can look like

- setBar:(BarClass*)bar {
  // Check needed to avoid getting ref count to 0 if setting the same object twice in a row.
  if (myBar != bar) {
    [myBar release];
    myBar = [bar retain];
  }

}

This looks a bit messy, and it kind of is. I’m not sure if this method decreases the risk of using freed memory compared to just using malloc and free like in C, but if it does then it’s definitely worth it. I’ve had a bunch of memory related issues when playing around with iPhone programming, but this was mostly when I was completely fresh to the language so I can’t really blame its design.

The garbage collection provided in OS X > 10.5 however works quite well, and I use it for all my OS X code. Hopefully the iPhone will get it as well eventually, but until then you’re stuck with ref counting.

No Private/Public/Protected

Objective-C doesn’t have the concept of private and public methods. All methods defined in a class header is public to callers. It is however possible to write implementations or even new declarations (using categories) inside of the implementation files which leaves the methods unexposed. In practice, it’s still possible to call them. You will just be given a warning during compilaton.

This also means that you can’t write protected methods like in Java (only accessible for it’s class and subclasses). If you want to expose a method to subclasses, you’ll have to expose it to the whole world as well. This will make some classes APIs a bit messier, but it’s not a major issue.

No modules

Objective-C uses something quite close to C++ for class dependencies. Headers work line in C/C++ but instead of including them with #include, you use #import which removes the need to check if the header was already included.

This means that you will still run into cyclic imports like in C or C++ if you have two classes Foo and Bar with dependencies on each other. To solve this, you use a new kind of forward references for the classes, and move the #import call to the classes implementation files like this

// Foo.h
@class Bar;
@interface Foo : NSObject
{
  Bar *bar;
}
@end
// Foo.m
#import "Bar.h"
@implementation Foo {
  /* stuff */
}
@end
// Bar.h
@class Foo;
@interface Bar : NSObject
{
  Foo *foo;
}
@end
// Bar.m
#import "Foo.h"
@implementation Bar {
  /* stuff */
}
@end

I’d really prefer to have module system like in Java.

Categories

Categories are a way to monkey patch code into existing classes. I find it pretty nasty from the design perspective, since it pretty much completely ignore the concept of encapsulation.

// NSStringExtras.h
#import "NSString.h"
@interface NSString (extras)
- (void)sayHello; // Extends the Cocoa string class with a hello world method.
@end

They can be used in a few quite nice way though. One of them is declaring categories for a class inside it’s implementation. This makes it possible to declare methods which will appear private, which “fixes” the lack of privacy in Objective-C.

// Foo.h
@interface Foo : NSObject {
}
- (void)publicMethod;
@end
// Foo.m
@interface Foo (hidden)
- (void)privateMethod;
@end

@implementation Foo
- (void)publicMethod {
  [self privateMethod];
}
@end

@implementation Foo (hidden)
- (void)privateMethod {
  NSLog(@"Hello world");
}
@end

No abstract classes

You can’t make abstract classes in Objective-C. You can do hacks which makes it impossible to initialize the “abstract” base class, but the concept of abstract classes doesn’t exist . This is rather ugly.

Networking Programming with Cocoa

Cocoa doesn’t have a nice Socket class like in Java. You are instead given a few different options for networking including CFSocket (which is a C API), raw BSD sockets and NSSocketPort which is pretty poorly documented and lacks support for UDP.

The lack of a proper Socket class in the standard library is solved by asyncsocket though, which makes socket handling a lot less painful. Something like this should probably be in the standard library in my opinion.

Xcode and Interface Builder

Xcode is the IDE shipped with the OS X dev tools. It’s pretty decent, but has a few shortcomings. One of them is the revision control integration. Xcode has some support for it (CVS/SVN/Perforce), but it’s pretty lacking and it seems like a lot of people use external tools for their needs. If you just want to commit and fetch updates from a single branch then it’s probably good enough, but if you want to do more advanced stuff you’ll have to do it by some other means.

The unit-test integration is also quite lacking. Getting a test suite up and running is way more work than it should be, and I still have to do some work arounds to be able to use the debugger while running tests.

The debugger is otherwise quite nice. It wraps GDB and I haven’t had any major issues with it.

Interface Builder is the design tool used for laying out OS X/iPhone GUI’s and I actually really like it. The way it lets ju bind you GUI items to your application controller is easy to learn and quite powerful. It’s actually probably my favorite WYSIWYG editor for a compiled language.

KVC/KVO

Essentially built in support for the Observer pattern for all objects. Quite useful, even though it like most parts of Cocoa isn’t as strict as when utilizing the pattern in many other languages.

Testing

It seems to me like very few Cocoa developers seem to use unit tests. I’ve been trying to keep a reasonable test coverage, and the testing tools OCUnit and OCMock are rather decent. The backwards compatibility with C makes OCUnit a bit iffy at times, but other than that I think it’s ok.

Documentation

The Cocoa documentation is for the most part excellent, but surprisingly a bunch of stuff lacks online documentation completely (try searching for docs on the core audio matrix mixer for an example). Usually there’s some kind of example to get you started though.

The community

The online community for OS X development is pretty good. There are a few online resources such as cocoadev which contains tons of good data. The #macdev and #iphonedev IRC channels on freenode are also excellent (especially Psy|). Finally, the related apple mailing lists provides a lot of information about topics which aren’t really covered elsewhere.

If you are forced to use Core Audio for an example, be prepared to search through the mailing lists for help a lot.

Summary

I don’t really know what I think about Objective-C. It’s design is a lot less strict compared to C++ and Java, and I don’t know if I like it or not. It works just fine though and I can’t blame Apple for deciding to use it as the standard language to use for OS X dev stuff. It is however quite complex to get to know the correct way of doing stuff when using Cocoa. It took me quite some time until I fully understood the KVO mechanic which makes Cocoa bindings work and so on.

Something I know that I like though is Xcode. It has some shortcomings (mainly revision control), but it’s an awesome IDE which allows for very rapid development thanks to Interface Builder which is excellent.

If I’d have to summarize my opinion, I’d say that I’m cautiously positive to doing OS X development. I don’t hate it after six months, and that’s actually somewhat impressive.

buffi Cocoa, Programming & scripting, Uninteresting , ,

Cocoa unit testing with OCUnit and OCMock: Mocking out IBOutlets

June 27th, 2009

I’ve been doing Objective-C (Cocoa) development for OS X at work now for just under a month, and I’m probably going to start pasting some useful snippets here on the blog.

One thing that I had some issues getting to work when I started writing unit tests for my code was IBOutlets for objects that were instantiated through the interface builder. These will only have their bindings setup when initializing the class with loadNibNamed from NSBundle or something similar. This is a bad idea during unit tests since it makes your tests depend on other classes. It is also rather slow.

Instead it’s better to just inject the IBOutlets manually.

The starting point

Let’s pretend I have a class called GameEngine whose interface and implementation looks something like this.

// GameEngine.h
@interface GameEngine : NSObject
    {
        // Handled by interface builder bindings.
        IBOutlet EnemyManager *enemyManager;
    }
    - (void)updateEnemies;
@end
// GameEngine.m
@implementation GameEngine
    - (void)updateEnemies
    {
        [enemyManager update];
    }
@end

If I were to test updateEnemies, I would have to detect if update was called for the enemyManager. If I just initate a GameEngine in my tests like the example below, enemyManager will not be hooked up (due to the lack of reference to the nib file which hooks up the bindings). This means that there’s no way to see what actually goes on inside the class.

One might think that this could be an issue, but it’s actually quite nice once you apply some additional test code.

Injecting the IBOutlet bound object

To setup you IBOutlets in your tests, you simply have to add an additional initializer as a category in your test code. This wont expose any additional initializer in the classes API outside of the tests, and it will allow you to replace the outlet bindings with mocks.

// GameEngineTestCases.m
@interface GameEngine (testing)
    - (id)initWithEnemyManager:(EnemyManager*)manager;
@end 

@implementation GameEngine (testing)
    - (id)initWithEnemyManager:(EnemyManager*)manager
    {
        self = [self init];
        enemyManager = manager;
        return self;
    }
@end

@implementation GameEngineTestCases
    - (void)testUpdateEnemies
    {
        id mockEnemyManager = [OCMockObject mockForClass:[EnemyManager class]];
        [[mockEnemyManager expect] update];
        GameEngine *engine = [[GameEngine alloc] initWithEnemyManager:mockEnemyManager];
        [engine updateEnemies];
        [mockEnemyManager verify];
    }
@end

Now you’re safely able to test your class without having to worry about nib files or external classes.

buffi Uninteresting

CVS is cute

June 21st, 2009

I played around a bit with Wireshark yesterday, and the initial server response when connecting to a CVS server is pretty cute.

CVS is cute

Unfortunately I’m guessing that nobody loves CVS anymore…

buffi Uninteresting

Job GET! (and some short book reviews)

May 17th, 2009

Like I mentioned in a previous post, I got my Master’s degree earlier this year. Since then I’ve been taking some courses at the University while looking for a nice place to work. In other words, I’ve mostly been slacking around :)

About two months ago I decided to browse through a Swedish job database and found an opening as a programmer at Interactive Institute: Sonic Studio which seemed quite cool. I sent in my CV, went on some interviews and finally signed the hiring papers about 1-2 weeks ago. My first day on the job is about a week from now, and I’m really looking forward to it.

Since Sonic Studio is positioned in PiteÃ¥ which is about 50km from LuleÃ¥ (where I live) by car, I’m currently browsing for a decent used car to purchase. This sucks quite a lot since my knowledge in cars is pretty much limited to knowing where the motors and wheels are positioned, but hopefully I’ll be able to work this out since the other option is taking the bus which leaves me with about thirty less minutes sleep in the mornings.

Otherwise I’ve done a bunch of small stuff during the latest months. Among other things, I started coding on a game-engine for shoot-em-up development since I’ve been wanting to build one of those for some time, and I felt the need to brush up on my C++ after doing a bunch of Java and Python development. This is pretty much just a pet-project that I’ve been playing around with occasionally when I get bored, an early proof of concept video is available here in case someone would be interested in that.

I’ve also been reading a bunch of nerd-literature. Since I’ve played around a bit with C++ again, I finally decided to read through Thinking in C++ which helped me brush up on my syntax, among other things. In my opinion, it is a pretty great book for learning and improving ones skills in C++ but I haven’t really read any other books about the language to compare it to.

When I finished up that book, I started with The Pragmatic Programmer which has been on my “to read list” for some time. The book is essentially a list of tips for developing software, where some of them might seem obvious but others actually forces you to rethink your development process. One of them which I know that I’ve made myself guilty of occasionally is the tip they call “Leave no broken windows”. The real world example given in the book is a car that is left in the streets. The car can be left alone for quite some time but once the first window is destroyed, the rest of the car is usually plundered and vandalized within a short span of time. The same hold true for software, and I have personally ignored small bugs to find them come back with friends later on to torture me. Once you start compromising your code quality, it usually snowballs and gets worse quite fast.

It touches a lot on the non-programming aspects of development as well, such as making sure that you gather the correct requirements for you project and use proper tools such as revision control. Of course there are a lot of other great tips in the book as well, and I’d recommend it to pretty much anyone who are involved with development of software.

Finally I’ve read a new book on lighttpd. As I’ve written previously in the blog, I’ve migrated most of my web-stuff from Apache to lighttpd and I couldn’t be more pleased. Setting up lighttpd is a lot easier than setting up Apache, so you wont really need a book for it but I’d definitely recommend it to anyone who either wants a good guide for setting it all up or just tuning an existing installation. It covers a wide arrange of topics including setup, encryption, DOS-protection and migration from other web servers. All in all, it isn’t an essential book for anyone who wants to run an lighttpd-installation but I’d recommend it since it beats the online resources in readability.

buffi Programming & scripting, Python, Uninteresting, Web development , , ,

College Degree GET!

February 2nd, 2009

I got my degree today (Master of Science in Computer Science and Engineering).

Master's Degree in Computer Science and Engineering

buffi Uninteresting

Google is broken

January 31st, 2009

Google = broken

Apparently I’m harmful for your computer.

buffi Uninteresting

Update! (TL;DR warning)

January 29th, 2009

I haven’t posted anything on the blog in close to a year, but I’m in the mood to start blogging a bit again so I guess I’ll post an update on what I’ve been doing since last year.

I got engaged to my girlfriend Li in May last year, and we moved into a new apartment some time around July (if I remember correctly). It is about the same size as the one we lived in earlier, but it looks a lot nicer and is in a better neighborhood, within walking distance of central Luleå. Some pictures of the new place below:

In June I started working on my Master’s Thesis as an intern at Google in LuleÃ¥. I worked together with the Gmail voice and video chat team for six months, and it was an awesome experience which I would recommend to anyone. I learned a LOT during these months and I’m pretty sure that it would be close to impossible to find a better place to perform an internship as a CS student. Unfortunately, in January (about a month after the end of my internship) Google announced that they are closing the LuleÃ¥ office which is a shame. I guess that it isn’t very cost-effective for Google to keep around small offices like this, but it was in my opinion an awesome office with very talented people and I feel privileged to have been able to perform my Thesis there while it was still around.

Since the end of my internship I’ve been waiting for the administrative personal at my University to finalize my graduation papers, and I will apparently receive them in about a week which makes my a MASTER OF SCIENCE (which unfortunately isn’t quite as awesome as it sounds). Since I will graduate that means that I will have to start looking for work… and yeah, graduating right in the middle of a “financial crisis” isn’t really timed very well :( .

I’m currently mostly looking for jobs around LuleÃ¥ since I really like it here, but I guess that I’m not completely against relocating if I have to (it beats going unemployed). For now I’m reading some extra courses (tuition is free in Sweden, and we actually receive money for studying here unlike those silly Americans who have to pay for everything) and working my old part-time job as an IT admin at the University. At least that leaves me with a bunch of spare time.

Except for all that I haven’t really been up to a whole lot. I’ve been playing a whole lot of video games, since October-November 2008 was pretty insane with a bunch of great releases. Since I had a bunch of free time at the end of the year I ended up playing through Dead Space, Mirrors Edge, Valkyria Chronicles, Fallout 3, Prince of Persia, Fable 2, Little Big Planet, Gears of War 2 and probably a bunch of other stuff that I’ve forgotten about… and that’s just counting retail games. I’ve played PSN games like crazy as well and I’ve maxed out a whole bunch of games including Astro Tripper, Lumines Supernova and Minna no Putter Golf with Toro.

In December I also purchased my first DSLR camera, a Nikon D40. Photography seems interesting, but I’m still pretty shitty at it. It’s nice to have a decent camera to play around with though. If I manage to snap something decent I might post it in the blog.

My current courses aren’t really that challenging and I’m currently only working about eight hours or so per week, so in the nearest future I’ll most likely continue looking for nice jobs, hammer away at some software projects I have ideas for and play a shitload of video games since Street Fighter 4, Killzone 2 and Resident Evil 5 is right around the corner.

Hopefully I’ll have time to update this blog more often as well (if anyone actually reads it).

edit: Oh yeah, I traveled to Amsterdam and Zürich during the summer as well. Amsterdam was a lot nicer than Zürich.

buffi Uninteresting

buffis.com back online

July 25th, 2007

Got myself a new server for buffis.com, since the old one died and I want to keep wordpress away from my “real” server since I don’t really trust it’s security.
2.80GHz of pleasure with 1gb of ram should be nice enough for playing around a bit, and it was free. Free is nice.

buffi Uninteresting

Logics exam in a week :(

May 21st, 2007

I’m supposed to be able to read this to understand how the hell I’m supposed to solve a bunch of problems in a course on logics I’m reading

10 pages of this. It doesn’t even look like western letters.
I hate logics (the teachers handwriting doesn’t help) :(

buffi Uninteresting

Comments are enabled

May 14th, 2007

Ok, I’m gonna try out the spamkarma 2 plugin to see if it works nicely.
I had too much spam before to be able to keep comments enabled, but this seems really nice so let’s give it a try.

buffi Uninteresting