views:

143

answers:

2

Let's say I am writing a class in Cocoa to act as a proxy to a server. To represent the current state of the connection, consider the enumeration:

enum
{
    MyConnectionStatusDisconnected = 0,
    MyConnectionStatusConnecting,
    MyConnectionStatusConnected,
    MyConnectionStatusCount
};
typedef NSUInteger MyConnectionStatus;

I may have it live in my proxy class like so:

@interface ServerProxy : NSObject
{
    MyConnectionStatus connectionStatus;
}

That's fine, but what if I want to figure out a user-readable interpretation of the connection status? I might have a static function like this:

+(NSString*)statusStringForInt:(MyConnectionStatus)status;

At this point I'm quickly leaving the realm of object-oriented programming.

What would be the best way to refactor this enum into a class hierarchy?

A: 

Please see http://stackoverflow.com/questions/1242914/converting-between-c-enum-and-xml. It's the same answer.

Ken
It's not really the same question. The answers also look identical to my question. The problem is how to make this into a clean hierarchy.
Shaggy Frog
I thought you were after a method that returns a class with the same name as the enum. If you're asking about getting rid of the enum entirely in favor of a class hierarchy, I think people will need more detail. It's not clear what the barriers to using classes are for you.
Ken
I'm not sure what more detail I can really offer. What I wrote was a working solution, but one that is really not object-oriented and looks clumsy to me. I don't know what you mean by barriers. What I'm looking for is an example refactoring, or perhaps a relevant pattern, hopefully done in Cocoa.
Shaggy Frog
For example, the implementation of `statusStringForInt:` will have a switch statement depending on the current value of `connectionStatus`, which is a code smell that it should be done with polymorphism. I'm familiar with design patterns in C++, but in Cocoa, I'd prefer someone show me a best practice before I go re-invent a square wheel.
Shaggy Frog
+1  A: 

I wouldn't refactor it into a class hierarchy. Instead, use NSString constants:

// foo.h
extern NSString *MyConnectionStatusDisconnected;


// foo.m
MyConnectionStatusDisconnected = @"Connection Status: Disconnected";

isEqualToString: does pointer equality as the first test so this will be fast.

You can then use Connection Status: Disconnected in your strings file(s) if you need to localize.

bbum