Inheritance/design advice in Objective-C - objective-c

Before I begin, I should probably mention that this sort of thing should probably have been implemented using the Core Data framework, but that is out of the question now.
We have data objects that are retrieved from a web service, and I'm trying to build a hierarchy for them, but I'm struggling.
I figured my base class should be called DataEntity, and defines an abstract property called EntityId and implements the hash method based on the entityId.
Any object retrieved from the web service can be implemented in one of two ways: By passing an NSDictionary to an entity, and letting it use that as its data source, or by passing the dictionary to an entity and letting it initialise its own data members from the dictionary. I have called these two types of entities DictionaryBackedDataEntity and ConcretedDataEntity. So my hierarchy would then be:
DataEntity -> DictionaryBackedDataEntity
-> ConcreteDataEntity
Then, consumers of this package/framework would only really care about the data members that are available to it, so I have created a protocol for each data type retrievable from the interface. So, for example, I could have a and an protocol, and these would have the data members that the DataEntity should expose.
So then, my hierarchy would look like this:
DataEntity -> DictionaryBackedDataEntity -> DictionaryBackedPerson <Person>
-> DictionaryBackedAnimal <Animal>
-> ConcreteDataEntity -> ConcretePerson <Person>
-> ConcreteAnimal <Animal>
Now, to be honest, I'm not sure whether I should be doing the above, or something like the below:
DataEntity -> PersonEntity -> DictionaryBackedPerson
-> ConcretePerson
-> AnimalEntity -> DictionaryBackedAnimal
-> ConcreteAnimal
In the above, PersonEntity and AnimalEntity would be abstract classes, and so instances would either be DictionaryBacked or Concrete instances.
Does anyone have any experience or recommendations on how I should approach this? I seem to be going around in circles and can't settle on a decision...
Regards,
N

Why not just have a single class DataEntity that stores it's property values in a dictionary? I think you probably don't need (and probably shouldn't require) to differentiate between ConcreteDataEntity and DictionaryBackedDataEntity.
#interface DataEntity
#property ( nonatomic, retain ) NSMutableDictionary * properties ;
#end
#implementation DataEntity
#synthesize properties ;
#end
#interface Animal : DataEntity
#property (nonatomic) NSUInteger numberOfLegs ;
-(id)initWithDictionary:(NSDictionary*)dict
{
if (( self = [ super init ]))
{
self.properties = dict ;
}
return self ;
}
#end
#implementation Animal
-(void)setNumberOfLegs:(NSNumber*)n
{
[ self.properties setValue:n forKey:#"numberOfLegs" ] ;
}
-(NSNumber*)numberOfLegs
{
return [ self.properties valueForKey:#"numberOfLegs" ] ;
}
#end
As a start...
You can save yourself some typing by using some of the more dynamic features of Obj-C here...
Look here: https://github.com/davedelong/Demos/tree/master/DynamicStorage

I definitely would NOT create the inheritance hierarchy you mentioned. You want to create inheritance based on the behavior of the class, not the underlying implementation for its internal data. You will end up with a class explosion as you add more classes that inherit from those bases and/or add more base implementations. Imagine you later have 3 types of base classes, one using the dictionary, one getting its dictionary passed in but using properties and fields, and a 3rd that uses another object or xml document or something. Then if you needed Person, Animal and Thing classes, you'd end up with 9 different classes total. DictionaryBackedPerson, ConcreteBackedPerson, ObjectXmlBackedPerson, etc. etc.
I would make one base class. Make it always have its own properties, but the ability to dynamically populate them using a dictionary if its passed, or vice versa as nielsbot mentioned. You could loop over a dictionary and call matching property names to set the values if needed.

There is nothing wrong with either approach from the information you have provided. But there are two schools of thought from what I can see.
The first is to take a technical approach which is your first example where you use DictionaryBackedDataEntity and ConcreteDataEntity. This is where your classes are representing how things have been implemented. I've seen a lot of this approach and generally speaking I'm not really a fan. Once your code gets larger and involved more classes this approach can have problems with clarity because it does not represent the application domain, but the implementation domain. ie. you end up with many (hundreds even) classes all built around their implementations, making it hard to discern what they are doing for your program.
The second approach (PersonEntity and AnimalEntity) is I think a more practical approach because it talks about your applications context and simply by looking at the names you immediately understand what they are for. In code, simplicity and clarity make for faster development and easier maintenance.
But the real truth I think is that you are likely to need a mix of both approaches in your code base. Often you need to develop small and abstract classes which don't necessarily manifest in your problem domain directly, but go a long way towards providing infrastructural code that supports other classes. These are good candidates for naming based on their technical aspects. Often too, this is code that can be split out to a separate project and built as a framework for use across multiple applications.
Finally, which design you choose will also come down to implementation code as well. For example, depending on the internals of your entities, you might be able to go with the first approach, but modify it so that that Person and Animal are categories on DataEntry rather than another layer of classes.
My final piece of advice would be to not get too hung up on which to do. Pick the one that feels the most comfortable to you and go with it. If at a later stage it's proves to be less that optimal for some reason, you can refactor to the other design. If nothing else, you will learn a bit about how you relate to code.

Related

iOS: is there a way to use a single class to hold common variables and not break Object Oriented principles?

I want to separate the data from the implementation in several classes, for many reasons.
One reason, for example, is that I have a few different menu screens that display text. I want to have one class that lists all the text for all the menus in one place, and then have the different menu objects read from that class when they initialize.
That way, whenever I want to make changes, I know exactly where the text variables are, and if I want to, I can change a bunch of them all at once.
I want to use the same principle in a lot of different ways, for example, setting the color and alpha values of various UIViews; having them all in one place would enable me to coordinate their settings and make small adjustments very easily.
Added to these reasons is that I'm working with a small team of other developers, and if we all know we're storing this kind of information in one place it's easier to understand each other's code.
So basically I want one big UberData class that every other class can read from and write to.
As far as I can figure, the only way to do this is make each of the needed variables a property, so I'll basically have a big methodless class with a heck of a lot of properties. But to my understanding, that's kind of bending the OO rules, because as much as possible classes should hide their innards. Not to mention the whole things seems really kludgey.
So the question is: is there a better way to do this than having the class with a million properties, and is it even proper to do it, from an OO perspective, at all?
One big UberData class (and really, if you are thinking properties, you mean one instance of that class) is the wrong approach.
What do menu strings and view colors have to do with each other? Nothing. Therefore they don't belong in the same class.
Strings
For your menu strings, look into the NSLocalizedString macro and creating a strings file. You could create a CommonStrings class that wraps all of your calls to NSLocalizedString:
#interface CommonStrings : NSObject
+ (NSString *)open;
+ (NSString *)save;
// etc.
#end
#implementation CommonStrings
+ (NSString *)open {
return NSLocalizedString(#"open", #"menu item title for opening a file");
}
+ (NSString *)save {
return NSLocalizedString(#"save", #"menu item title for saving a file");
}
// etc.
#end
This approach means you only write #"open" in one place, and then you refer to [CommonStrings open] when you need the (localized) string. The compiler checks that you've spelled [CommonStrings open] correctly, which is nice.
However, it's still probably better to break this into multiple helpers (one for each independent part of your app), rather than one giant helper for your entire app. If you use one giant catch-all class, then compiling your app takes longer because so much has to be recompiled every time you add or remove a method in this class.
UIView colors
First, watch the appearance customization videos from WWDC 2012 and WWDC 2013 and read up on UIAppearance. Maybe you can just use that to customize your app's colors.
If that doesn't suffice, create a category on UIColor for your app's colors:
#interface UIColor (MyApp)
+ (UIColor *)MyApp_menuBackgroundColor;
+ (UIColor *)MyApp_menuTextColor;
// etc.
#end
#implementation UIColor (MyApp)
+ (UIColor *)MyApp_menuBackgroundColor {
return [self colorWithPatternImage:[UIImage imageNamed:#"menuBackgroundPattern"]];
}
+ (UIColor *)MyApp_menuTextColor {
return [self colorWithWhite:0.0 alpha:1.0];
}
// etc.
#end
Again, it may be better to have multiple helper categories for different parts of your app, so you don't have to recompile as much when you add or remove a category method.
First off, forget "propriety". What is proper is what works, works reliably and efficiently, is easy to understand, and easy to maintain. Adhering to "object-oriented principles", while to some degree a worthwhile goal, should not cause you to do awkward, error-prone, and inefficient things. Just about any "programming rule" can be followed too literally.
Having dozens (or hundreds) of properties is clumsy and hard to maintain from several standpoints, so that's basically a non-starter.
More appropriate is having a few queryable interfaces that return the values you want. The "right" scheme often depends on the characteristics of the data, but one can, eg, have a method with a simple switch statement or "if ladder" that returns value Y given value X (where X is, eg, an enumeration value).
One can also have what is either actually or conceptually an NSDictionary which you query with a character "key" value.
A variation of that is a property list, which allows you to describe the data in a data file, vs having to code it into source. You can also put the data in a JSON file, if that suits your design and habits better.
And there are several other schemes that I've used in the past that aren't occurring to me just now.
Added:
OK, I'll give an example of something that is basically impossible with "macros" and "extern variables". In several cases, in some of the code I work on, there are objects that contain information about specific events. There may be 50 different categories of events, each with a different set of properties (sub-category, display color, text for various conditions, etc).
One could, of course, have several hundred declared constants, of the style "kXyzCategoryAbcSubCategory", "kXyzCategoryAbcColorMode", "kXyzCategoryAbcTitleText", etc, but maintaining is a PITA, and typos in use are routine. Plus it's not really usable, since you can't take "category" from the object and "index" the attributes.
Instead, I use one of two schemes:
A set of callable interfaces where you pass in the constant "kXyzCategoryAbc" (or the category value dynamically extracted from the object) and call one of several methods -- xyzSubCategory, xyzColorMode, xyzTitleText -- and the method returns the required data.
A callable interface where you pass in the category value and it returns an NSArray (with keys, eg, of "subCategory", "colorMode", and "titleText").
Both of these techniques work pretty well, though one or the other may be preferred depending on circumstances. Both allow you to maintain the data as a table of some sort, and allow you to use the same constant to fetch multiple values, vs having to introduce 50 new constants when you add one new attribute to one of your category objects.
You shouldn't use a class for this at all. Use macros for code internal constants, and extern variables for values that can change.
Note: User visible strings should be done through localization files -- see the other answers.
When it comes to constants, I usually have a CPConstants.h (CP being my class prefix) file that looks something like this:
#define kCLConstant1 42
#define kCLColorConstant [UIColor blackColor]
And so on.
If you need values to be changeable, first create a CLConstants.m file, like this:
#import "CLConstants.h"
int some_global_var = 42;
UIColor* some_global_changable_color = [UIColor blackColor];
And so on. Then, in CLConstants.h, add a line like this for every variable you declared in CLConstants.m:
extern type varname;
Now all files that include/import CLConstants.h can use and change those variables, and changes will be visible to all other files in the project.
Yes, the common response to a single, shared configuration object is the Singleton pattern. Briefly, a class method knows how to make or return an instance of the class and the instance knows how to configure the needed things. I think you will find many results from stack overflow by searching although What should my Objective-C singleton look like? is one easy example.
Beyond that, I would encourage you to look into how localization works in iOS - the problem you initially reference of having a source for menu titles and things is one that the localization library has solved for you, and in an extensible way.
You may also want to look at property lists (aka, plists) which is a structured data file that can be easily read in iOS applications.
You basically have two choices in sharing data across several controllers:
1) Use a singleton
In this instance, a singleton data model sounds appropriate. (A singleton data model is a single, shared instance of a data model used by several controllers.)
As you mentioned, however, you may indeed wind up with a class that has lots of properties by doing this... there's nothing wrong per se about this, however. Just be choosy in the properties that you have on the singleton... if it's not shared by several controllers, it probably shouldn't be there.
See Apple's documentation on how to create such here.
Here's another SO post about Singletons in iOS.
2) Use a header (.h) file in which you define all your shared variables, then import this wherever you need them (or put into the .pch file to be automatically imported everywhere in your project).
Typically, this is done using static constant variables. I'd imagine you could possibly do this via just static variables so that you can edit them, but at least the last I checked, the compiler may give incorrect unused variable warnings.

The Magician and the custom class – understanding the header and implementation file

I am taking my first stumbling steps in the Objective-C world together with a book on the subject. I have now come to the stage in which to internalize the concept of creating and using a custom class.
And as I guess that understanding these fundamental concepts and principles correctly is key to my future learning of Objective-C, I just wanted to check with you if have grasped the concepts somewhat correctly.
So when creating a custom class, I have understood that this is done in two separate files – the public class header file, and the class implementation file. And in order to internalize this concept, I have metaphorically understood this with a parallel to a “magician” doing its tricks in front of an audience.
The header file is somewhat like the poster outside the theatre where the magician performs. Before entering, we can all see what the magician looks like (the properties) and what tricks he (it’s mostly a “he”) can perform (the methods), and on what types of stuff he can make his magic tricks (type declaration). Thus from this “public” poster (the header file) of the magician, I can understand what kind of magic he can perform and what props he is using. Maybe there is also a mentioning of that this particular magician has learned some of his tricks from the great Houdini (the class heritage and Houdini thus being the superclass).
If I were allowed backstage, I would then be able to actually see how he is doing his tricks, that is, I would be able to look in the magicians implementation file.
Would this metaphor be somewhat along the lines of how you can understand the concept of a custom class?
However, I have not yet quite figured out how the concept of class methods and instance methods relates to this metaphor?
Could you say that instance methods belongs to a category of tricks that this particular “instance” of the magician is performing in this particular show, and the class methods would be the tricks that contemporary magicians can perform?
Thirdly, it is a bit confusing the way methods are using “types”. Some seem to be declared up front in the interface file, and some seem to just be “declared” on the fly within the methods?
To take an example using the “Magician” class, my understanding of the header file might look like this:
#interface Magician : NSHoudini
// Instance method that given a variable of type rat it will turn this into something of type rabit
- (rabit) FromRatToRabit: (rat) aRat;
#end
And the implementation file might look like this:
#import “Magician.h”
#implementation Magician
rabit aRabit
// rabit being the type and aRabit the variable
- (rabit) FromRatToRabit:(rat)aRat;
{
// some magic code goes here which will take what’s in the aRat variable, of type rat
// and turn it into a form of type rabit and return it in the aRabit variable
aRabit
}
#end
If above is correct I wonder why the aRat variable that you “feed” the method with is not declared? Or is the declaration considered done when you are using it in the method description?
Your metaphor is acceptable. A header is an interface for other files to look at which tell them what is accessible to them from that class/file and its corresponding implementation file (if it has one)
I noticed in your code though that Magician is a subclass of Houdini. I might just be misunderstanding your example, but in terms of inheritance, that is probably incorrect. What you are saying there is that every Magician is a type of Houdini. It should probably be reversed to say that Houdini is a type of Magician.
Class vs Instance has been explained many times and is not specific to Objective C, so I won't get into it too much.
Here is a post with some good answers. Basically, a class function/variable belongs to the Class itself, and is not specific to any instance of that class. Another word for a class function/variable is a static function or variable.
Not sure what you mean by the last question. Every pointer/variable in objective c has a type.
Your syntax is messed up though, Here is what the code you posted should probably look like (and yes I corrected the spelling of rabbit :-P)
#interface Houdini : Magician
// Instance method that given a variable of type rat it will turn this into something of type rabit
- (Rabbit *) FromRatToRabit: (Rat *) aRat;
#end
#import “Houdini.h”
#implementation Houdini
Rabbit *aRabbit; // this is an ivar, although you're not actually using it anywhere, I'm just correcting your syntax
- (Rabbit *) fromRatToRabit:(Rat *)aRat;
{
// some magic code goes here which will take what’s in the aRat variable, of type rat
// and turn it into a form of type rabit and return it in the aRabit variable
[aRat doSomethingToReturnRabbit]; // assuming rat has an instance function that returns a rabbit
}
#end
And you could use this function by doing something like
Houdini *myHoudini = [[Houdini alloc] init];
Rat *houdinisRat = [[Rat alloc] init];
Rabbit *houdinisRabbit = [myHoudini fromRatToRabbit:houdinisRat];
Note that this depends on there being a rat class and a rabbit class (which you did not provide). I am also just using what are normally the default initializers.
Hopefully this helps, you should try searching more on the specific topics you have questions on individually, because there is plenty of reading available.
It's a great metaphor for understanding the divide between the public interface and the hidden implementation. But I think you might be getting a bit wrapped up in it and I do see two major misunderstandings - "Houdini" being the superclass and the class methods being "all tricks".
The common textbook way to evaluate the sensibleness of an inheritance hierarchy is to evaluate whether a subclass instance "is a" superclass instance. This can get very abstract in reality but if, say, you're designing the Magician's Guild medical insurance benefits processing software or something, in that context a Magician "is a" something that's definitely not a Houdini! Say they are all freelancers so every Magician "is a" 1099 Contractor (US tax form for self-employment income), or something like that. Another way to think of it would be to think Magician "is a" Stage Performer, which "is a" Entertainer, and so forth. Not that you always want to make software like this but it can help for learning the concept I suppose.
The second thing you said you were struggling with was how to think about class methods. Consider class methods behavior and information inherent to the type, and independent of any instance. Going back to the benefits software example, lets say all Magician guild members get a 401k (another US tax code thing, retirement account) with $X defined contribution per paycheck. Now assuming that's not something that varies with seniority, this would be a good piece of information to keep at the class level. So, all the tricks a magician can perform would not be class methods - Magicians perform them, so they would be instance methods. Perhaps a list of banned tricks (for being too dangerous) could be a class method - it's a rule inherent to being a Magician but is independent from any single magician.
Finally, to your third question about types, I can sort of guess at what you're asking but am not sure. Say you have a method
- (void)myMethod:(id)myArgument
{
NSLog(#"myArgument = %#",myArgument);
}
Then are you asking where myArgument is declared? It is declared right there in the method signature, where it's a parameter to the method and you can refer to it in its scope of the method body (within the curly braces). Not sure if that's what you meant by "on the fly" or not. I'm afraid you'll have to provide some actual source code, not pseudocode, and point out specific places you're wondering about.
And a couple of minor points on terminology, sorry this is getting so long - the term for "feeding" a value to a method is "passing" usually as a "parameter" or an "argument". The method "description" is usually called a a method signature, or declaration, sometimes prototype I hear. And yes, please clarify what you're talking about with types, type declarations, and so on, I'm not 100% clear on your questions there.
Hope this helps!

Worker vs data class

I have a data class which encapsulates relevant data items in it. Those data items are set and get by users one by one when needed.
My confusion about the design has to do with which object should be responsible for handling the update of multiple properties of that data object. Sometimes an update operation will be performed which affects many properties at once.
So, which class should have the update() method?. Is it the data class itself or another manager class ? The update() method requires data exchange with many different objects, so I don't want to make it a member of the data class because I believe it should know nothing about the other objects required for update. I want the data class to be only a data-structure. Am I thinking wrong? What would be the right approach?
My code:
class RefData
{
Matrix mX;
Vector mV;
int mA;
bool mB;
getX();
setB();
update(); // which affects almost any member attributes in the class, but requires many relations with many different classes, which makes this class dependant on them.
}
or,
class RefDataUpdater
{
update(RefData*); // something like this ?
}
There is this really great section in the book Clean Code, by Robert C. Martin, that speaks directly to this issue.
And the answer is it depends. It depends on what you are trying to accomplish in your design--and
if you might have more than one data-object that exhibit similar behaviors.
First, your data class could be considered a Data Transfer Object (DTO). As such, its ideal form is simply a class without any public methods--only public properties -- basically a data structure. It will not encapsulate any behavior, it simply groups together related data. Since other objects manipulate these data objects, if you were to add a property to the data object, you'd need to change all the other objects that have functions that now need to access that new property. However, on the flip side, if you added a new function to a manager class, you need to make zero changes to the data object class.
So, I think often you want to think about how many data objects might have an update function that relates directly to the properties of that class. If you have 5 classes that contain 3-4 properties but all have an update function, then I'd lean toward having the update function be part of the "data-class" (which is more of an OO-design). But, if you have one data-class in which it is likely to have properties added to it in the future, then I'd lean toward the DTO design (object as a data structure)--which is more procedural (requiring other functions to manipulate it) but still can be part of an otherwise Object Oriented architecture.
All this being said, as Robert Martin points out in the book:
There are ways around this that are well known to experienced
object-oriented designers: VISITOR, or dual-dispatch, for example.
But these techniques carry costs of their own and generally return the
structure to that of a procedural program.
Now, in the code you show, you have properties with types of Vector, and Matrix, which are probably more complex types than a simple DTO would contain, so you may want to think about what those represent and whether they could be moved to separate classes--with different functions to manipulate--as you typically would not expose a Matrix or a Vector directly as a property, but encapsulate them.
As already written, it depends, but I'd probably go with an external support class that handles the update.
For once, I'd like to know why you'd use such a method? I believe it's safe to assume that the class doesn't only call setter methods for a list of parameters it receives, but I'll consider this case as well
1) the trivial updater method
In this case I mean something like this:
public update(a, b, c)
{
setA(a);
setB(b);
setC(c);
}
In this case I'd probably not use such a method at all, I'd either define a macro for it or I'd call the setter themselves. But if it must be a method, then I'd place it inside the data class.
2) the complex updater method
The method in this case doesn't only contain calls to setters, but it also contains logic. If the logic is some sort of simple property update logic I'd try to put that logic inside the setters (that's what they are for in the first place), but if the logic involves multiple properties I'd put this logic inside an external supporting class (or a business logic class if any appropriate already there) since it's not a great idea having logic reside inside data classes.
Developing clear code that can be easily understood is very important and it's my belief that by putting logic of any kind (except for say setter logic) inside data classes won't help you achieving that.
Edit
I just though I'd add something else. Where to put such methods also depend upon your class and what purpose it fulfills. If we're talking for instance about Business/Domain Object classes, and we're not using an Anemic Domain Model these classes are allowed (and should contain) behavior/logic.
On the other hand, if this data class is say an Entity (persistence objects) which is not used in the Domain Model as well (complex Domain Model) I would strongly advice against placing logic inside them. The same goes for data classes which "feel" like pure data objects (more like structs), don't pollute them, keep the logic outside.
I guess like everywhere in software, there's no silver bullet and the right answer is: it depends (upon the classes, what this update method is doing, what's the architecture behind the application and other application specific considerations).

Share code between classes in Objective-C without inheritance?

Since Objective-C does not support multiple inheritance, is there some other mechanism to share code between classes?
I'm writing a Cocoa library on top of an existing xml schema. Many elements in the schema (for example, ) are used in multiple types. I was hoping to centralize this somehow, so that I didn't have to add #property NSString *name and the associated code to generate the xml for the name property in every single class that has a name attribute. That would be fairly straightforward if multiple inheritance were supported, but I don't know how to do it otherwise.
The best thing I can think of is to create a common superclass that has a superset of methods to encode each optional property, then call the appropriate methods (i.e. encodeName) in the encoding method for each class. Does that seem like the best way to go?
I would recommend you create a new Category with your properties/functions etc and add said category to NSObject. That would make all properties and functions available to all subclasses of NSObject. It's not exactly multiple inheritance but provides a great amount of flexibility.
It is actually possible to add data to a class at run time using the runtime's Associative Reference functions. It's a little deeper than normal SDK work, but works quite well. It's not the same as a full property with getters and setters, but it does associate objects with an instance.
If the methods are only required on certain objects then maybe a sub class from that class is the way to go or a category on that specific class would be better. The category on NSObject is quite a wide net to cast.
If you want to add additional state then sub classing is probably your safest bet.
If you do add a category make sure you prefix your methods with something unique so to avoid any conflicts. E.g. PSMySpecialMethod as opposed to mySpecialMethod

What is the difference between inheritance and Categories in Objective-C

Can some one explain to me the difference between categories and inheritance in Objective C? I've read the entry in Wikipedia and the discussion on categories there doesn't look any different to that of inheritance. I also looked at the discussion on the topic in the book "Open iPhone Development" and I still don't get it.
Sometimes, inheritance just seems like more trouble than it is worth. It is correctly used when you want to add something to an existing class that is a change in the behaviour of that class.
With a Category, you just want the existing object to do a little more. As already given, if you just want to have a string class that handles compression, you don't need to subclass the string class, you just create a category that handles the compression. That way, you don't need to change the type of the string classes that you already use.
The clue is in the restriction that categories only add methods, you can't add variables to a class using categories. If the class needs more properties, then it has to be subclassed.(edit: you can use associative storage, I believe).
Categories are a nice way to add functionality while at the same time conforming to an object oriented principle to prefer composition over inheritance.
Edit January 2012
Things have changed now. With the current LLVM compiler, and the modern, 64-bit runtime, you can add iVars and properties to class extensions (not categories). This lets you keep private iVars out of the public interface. But, if you declare properties for the iVars, they can still be accessed / changed via KVC, because there is still no such thing as a private method in Objective-C.
Categories allow you to add methods to existing classes. So rather than subclass NSData to add your funky new encryption methods, you can add them directly to the NSData class. Every NSData object in your app now has access to those methods.
To see how useful this can be, look at: CocoaDev
One of favorite illustrations of Objective-c categories in action is NSString. NSString is defined in the Foundation framework, which has no notion of views or windows. However, if you use an NSString in a Cocoa application you'll notice it responds to messages like – drawInRect:withAttributes:.
AppKit defines a category for NSString that provides additional drawing methods. The category allows new methods to be added to an existing class, so we're still just dealing with NSStrings. If AppKit instead implemented drawing by subclassing we'd have to deal with 'AppKitStrings' or 'NSSDrawableStrings' or something like that.
Categories let you add application or domain specific methods to existing classes. It can be quite powerful and convenient.
If you as a programmer are given a complete set of source code for a code library or application, you can go nuts and change whatever you need to achieve your programming goal with that code.
Unfortunately, this is not always the case or even desirable. A lot of times you are given a binary library/object kit and a set of headers to make do with.
Then a new functionality is needed for a class so you could do a couple of things:
create a new class whole instead of a stock class -- replicating all its functions and members then rewrite all the code to use the new class.
create a new wrapper class that contains the stock class as a member (compositing) and rewrite the codebase to utilize the new class.
binary patches of the library to change the code (good luck)
force the compiler to see your new class as the old one and hope it does not depend on a certain size or place in memory and specific entry points.
subclass specialization -- create subclasses to add functionality and modify driver code to use the subclass instead -- theoretically there should be few problems and if you need to add data members it is necessary, but the memory footprint will be different. You have the advantage of having both the new code and the old code available in the subclass and choosing which to use, the base class method or the overridden method.
modify the necessary objc class with a category definition containing methods to do what you want and/or override the old methods in the stock classes.
This can also fix errors in the library or customize methods for new hardware devices or whatever. It is not a panacea, but it allows for class method adding without recompiling the class/library that is unchanged. The original class is the same in code, memory size, and entry points, so legacy apps don't break. The compiler simply puts the new method(s) into the runtime as belonging to that class, and overrides methods with the same signature as in the original code.
an example:
You have a class Bing that outputs to a terminal, but not to a serial port, and now that is what you need. (for some reason). You have Bing.h and libBing.so, but not Bing.m in your kit.
The Bing class does all kinds of stuff internally, you don't even know all what, you just have the public api in the header.
You are smart, so you create a (SerialOutput) category for the Bing class.
[Bing_SerialOutput.m]
#interface Bing (SerialOutput) // a category
- (void)ToSerial: (SerialPort*) port ;
#end
#implementation Bing (SerialOutput)
- (void)ToSerial: (SerialPort*) port
{
... /// serial output code ///
}
#end
The compiler obliges to create an object that can be linked in with your app and the runtime now knows that Bing responds to #selector(ToSerial:) and you can use it as if the Bing class was built with that method. You cannot add data members only methods and this was not intended to create giant tumors of code attached to base classes but it does have its advantages over strictly typed languages.
I think some of these answers at least point to the idea that inheritance is a heavier way of adding functionality to an existing class, while categories are more lightweight.
Inheritance is used when you're creating a new class hierarchy (all the bells and whistles) and arguably brings alot of work when chosen as the method of adding functionality to existing classes.
As someone else here put it... If you are using inheritance to add a new method for example to NSString, you have to go and change the type you're using in any other code where you want to use this new method. If, however, you use categories, you can simply call the method on existing NSString types, without subclassing.
The same ends can be achieved with either, but categories seem to give us an option that is simpler and requires less maintenance (probably).
Anyone know if there are situations where categories are absolutely necessary?
A Category is like a mixin: a module in Ruby, or somewhat like an interface in Java. You can think of it as "naked methods". When you add a Category, you're adding methods to the class. The Wikipedia article has good stuff.
The best way to look at this difference is that:
1. inheritance : when want to turn it exactly in your way.
example : AsyncImageView to implement lazy loading. Which is done by inheriting UIView.
2. category : Just want to add a extra flavor to it.
example : We want to replace all spaces from a textfield's text
#interface UITextField(setText)
- (NSString *)replaceEscape;
#end
#implementation UITextField(setText)
- (NSString *)replaceEscape
{
self.text=[self.text stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
return self.text;
}
#end
--- It will add a new property to textfield for you to escape all white spaces. Just like adding a new dimension to it without completely changing its way.