Alex Rivera | Logout

Is subclassing in Objective-C a bad practice?

Asked 2009-05-09T22:21:32.570
17

After reading lots of blogs, forum entries and several Apple docs, I still don't know whether extensive subclassing in Objective-C is a wise thing to do or not.

Take for example the following case:

Say I'm developing a puzzle game which has a lot of elements. All of those elements share a certain amount of the same behaviour. Then, within my collection of elements, different groups of elements share equal behaviour, distinguishing groups from groups, etc...

So, after determining what inherits from what, I decided to subclass out of oblivion. And why shouldn't I? Considering the ease tweaking general behaviour takes with this model, I think I accomplished something OOP is meant for.

But, - and this is the source of my question - Apple mentions using delegates, data source methods, and informal protocols in favour of subclassing. It really boggles my mind why?

There seem to be two camps. Those in favor of subclassing, those in fafor of not. It depends on personal taste apparently. I'm wondering what the pros and cons are of subclassing massively and not subclassing massively?

To wrap it up, my question is simple: Am I right? And why or why not?

Edit
Report

1 Answer

3

I really think it depends on what you're trying to do. If the puzzle game you describe in the example really does have a set of unique elements that share common attributes, and there's no provided classes - say, for example, "NSPuzzlePiece" - that fit your needs, then I don't see a problem with subclassing extensively.

In my experience, delegates, data source methods, and informal protocols are much more useful when Apple has provided a class that already does something close to what you want it to do.

For example, say you're building an app that uses a table. There is (and I speak here of the iPhone SDK, since that's where I have experience) a class UITableView that does all the little niceties of creating a table for interaction with the user, and it's much more efficient to define a data source for an instance of UITableView than it is to completely subclass UITableView and redefine or extend its methods to customize its behavior.

Similar concepts go for delegates and protocols. If you can fit your ideas into Apple's classes, then it's usually easier (and will work more smoothly) to do so and use data source, delegates, and protocols than it is to create your own subclasses. It helps you avoid extra work and wasting time, and is usually less error-prone. Apple's classes have taken care of the business of making functions efficient and debugging; the more you can work with them, the fewer mistakes your program will have in the long run.

answered 2009-05-09T23:18:57.910

Your Answer