Tag Archive for 'Programming'

Opinion of Objective-C

Programming can be incredibly entertaining. And I don’t just mean finding hex arrays with 17 entries either. Programmers benefit from a wide range of languages — tools to get the job done. Sometimes, it’s easier to use one language over another (e.g. don’t write an app in C when a bash script will do). When asked about their favorite language, many nerdy types will probably throw out Ruby or Python. Generally speaking, only masochists will say Java or C. Whatever. Every so often, you’ll meet a crazy AND nerdy person who will respond Objective-C. I’m crazy and nerdy.

So Hamed asked if I wanted to help write the first Radio Javan iPhone app. Naturally, I said yes. At first, I wondered WTF was up with all the brackets. Don’t worry, they grow on you. The @ before NSStrings is a little strange at first too. I like it. In fact, I like it so much, I try to use it when writing other languages (O.o). Objective-C has other quirks, too, like the crazy-long-and-oddly-amusingly-verbose method names. I guess I’m trying to say that Objective-C is really cool and it’s a shame programmers are scared of it. Objective-C is just plain sexy (as far as programming languages go). I’ll admit that I’m not much of a fan of lower level languages, despite knowing their usefulness. Srsly, do yourself a favor and learn Objective-C.

Just Learn the Damned Language

I hear the same pitch, over and over: I have this widget. It lets you write <insert high level language that everyone already knows here> and it spits out <insert lower level language and its UI toolkit here>! It saves so much time and it’s easy and it lowers time to market and and and you can even write Java! There’s ALWAYS Java going on with these things, for some reason. NO! Bad idea.

Well, let me be clear about it. The idea itself isn’t so bad; it’s the HORRIBLE implementation that almost always comes along for the ride. There are exceptions, of course, but I contend they’re the minority.

There is generally some huge functional void since someone has to implement classes to fill functionality gaps where there isn’t a reasonable mapping between libraries of the two languages and they never quite finish. This makes using the widget not quite as good as learning the output language, not to mention having to learn the widget’s libraries, which are supposed to mimic the output language’s libraries (and they often don’t). Then, there are bugs. Lots and lots of bugs to terrify you and give you nightmares. Why not just spend a few days learning the language you need to use? Your engineering skills will get you through it.

Programming: Clever is good. Too Clever is Bad.

Sometime this week I was tasked with implementing some super-secret whiz-bang moderation tool for the Elf Island mod team. Since we’re big fans of code reuse (we have one hell of a dev team..you should have seen the code base when we inherited it 7 months ago…), I decided to piggy back off some functionality we added a few weeks earlier that supplied room list information to the client based on some filter parameters. The old code looked something like this:


for each (room in currentRooms) {
...
//Filter based on params
if (privateParam != room.isPrivate || room.isLimbo) continue;
...
}

This was clever because it let us filter one of two disjoint subsets in a single line given 3 parameters. Then came the natural extension (..oof..) of adding another param to get both sets for this whiz-bang feature.


for each (room in currentRooms) {
...
if (!allParam && (privateParam != room.isPrivate || room.isLimbo))
continue;
...
}

At first glance, this looked sensible. Unfortunately, it was brittle and fell apart when some “other” brittle code (that we did not control) did what average java developers do best (assume stupid things, eat exceptions, then throw nonsensical messages into logs). The issue was two things: the obvious order of operations issue and the larger problem of lack of intent expression. Sure it was fun to look at but it’s not easy to maintain. Had I refactored this into a separate method with a clearly defined flow, I wouldn’t have spent hours chasing my tail due to the aforementioned foolish error in the logs. The issue only cropped up under load (when the chance was ~100% a user was in a “limbo” room). The lesson to take from this post is to urge people to write readable code, even if it’s a tiny bit more verbose, instead of attempting to cram things like a 4 parameter filter with weird edge cases into a single line. Code should express intent and it should make sense at first glance, not try to get the job done in the least number of lines possible.

The opterator hated by most, loved by me: ternary

So I’ve heard it or read it at least 5 times in the past few days: everyone hates the ternary operator. Why? What’d it ever do to you? Wait wait, what’s the ternary operator? Srsly? You’re on my blog and you don’t know what it is? Ok, so normally one writes a conditional like this:


if (someCondition equals some value) {
do stuff;
} else
{
do other stuff;
}

Lots of code for not so much of anything else (outside of readability). Ok, so for those cases where the stuff and other stuff are single lines or some other simple deal (e.g. returning a boolean or integer value), the ternary operator is great. Take a look:


(someCondition equals some value) ? do stuff : do other stuff;

Look at how nice and neat that is — how’s it difficult to read? What if you want to set a value?


x = (someCondition equals some value) ? true : false;

So if someCondition equals some value, x is set to true, otherwise it’s set to false. Nothing difficult or complicated about it. There’s nothing hard to read about it either, imo. Having said all of this, don’t go doing something stupid like this (because it IS hard to read):


(someCondition equals some value and another Condition equals some value or .............. and ............. yada yada more conditions and stuff that eventually evaluates to a boolean) ? do a ton of stuff : do some other ton other stuff;

Bad. Skip it, keep things simple, and go with the regular conditional syntax. Trust me, other people will look at your code and some might even want to slap you for it. Anyway, don’t hate on the ternary operator. If it’s not your style, that’s fine, but you should know that it’s very useful and saves some typing. If people didn’t hate it so much, it would have saved me this blog post..but then again that would have been sort of boring.

NSURLConnection + timeoutConnection = Amdev Woes

So for the past two days I’ve had my iPhone app crashing and vomiting “EXC_BAD_ACCESS” in the console. Generally speaking, this error means you’ve released a reference to some object you still need and some other object tried to send a message to said object afterward. It turns out that it was entirely my fault and (GASP) paying a little more attention to Apple’s reference would saved hours and hours of debugging for me.

NSURLConnection is actually pretty simple to use but here are some tips:

  1. Use the asynchronous mode for any reasonably large file (bigger than a few KB) as people might be on a slow Edge network connection and locking up the view is never a good thing.
  2. Do not send the message “start” to your connection if you use connectionWithRequest or initWithRequest to initialize your connection as you’ll get the nasty “EXC_BAD_ACCESS” error mentioned above. The reason for this is simple:  You’ve scheduled your connection to time out in n seconds, the method that initializes the connection starts fetching data immediately. You then send the message “start,” which spins off the connection trying to fetch data again. This works fine except that the original attempt eventually times out and tries to call back, hosing everything over and crashing your application hard core. Oops. You should only send the message “start” to your connection if you initialize it with initWithRequest:delegate:startImmediately.
  3. When setting up NSURLRequest to pass to NSURLConnection, I highly recommend using NSMutableURLRequest so you can set the User-Agent header.  Some http servers may not return data, even for a simple GET without the User-Agent.  It’s my understanding that User-Agents are optional, but I do not know if said server behavior is nonstandard.

    NSMutableURLRequest *request  = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: @"http://myurl.com"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];

    //Borrow FF2’s User-Agent

[request setValue: @"Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.16) Gecko/20080702 Firefox/2.0.0.16" forHTTPHeaderField: @"User-Agent"];

I hope this saves someone some time.