Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Category, protocal, one big class? What should I use here

I am trying to implement a generic number class. Basically my app needs to receive a string from the user and parse it to determine if its imperial (ft in fraction or any combo of these) or if its metric (m cm mm or any combo). My idea was to make Metric & Imperial classes, both of which are of a more generic type Number. Then the UI creates a Number object passing in the string to parse, and the number determines if it is metric or imperial. I see how it would work easy making 1 large number class that does this, but it seems like I should separate the metric and imperial classes from the standard interface (Number) since they will do much more then just parse the string.

So if I do Number *num = [[Number alloc] initWithString:someString]; I would get a subclass of Number that is specific to Imperial or Metric. This is really where I know something isn't making sense, but I'm not sure how to do it.

What would be a good way to handle this?

like image 417
jamone Avatar asked Apr 26 '11 13:04

jamone


2 Answers

What do you think is wrong with your proposal?

What you want to do and how to solve it exactly matches a Cocoa concept called "class clusters", described in the Cocoa Fundamentals Guide. Apple uses this pattern all over the place in Foundation and AppKit.

like image 105
Nikolai Ruhe Avatar answered Nov 20 '22 04:11

Nikolai Ruhe


I would create a subclass of NSFormatter to do the conversion between strings and objects of your custom class. That way, you can associate the formatter with UI controls and then they will automatically give you objects of the right type.

How you implement your actual numbers depends. For instance, you could have a generic number class called Length and subclasses called LinegthInInches and LengthInMetres (say). Or you could go with one class that has a property called units that tells you whether the units are feet or metres or whatever. Or you could have a protocol that defines the required methods that any object must implement to be considered one of your numbers. That way you could conceivably add a category to NSNumber to make it conform to your protocol.

I would probably go with the first option i.e. flattish class hierarchy with a subclass for each unit type. Your NSNumberFormatter subclass would decide which number subclass to return based on the string it is given and it would format its strings based on the class of the number it was given.

like image 38
JeremyP Avatar answered Nov 20 '22 03:11

JeremyP