Extending vs declaring as Member?


#1

Two questions.

  1. Does anyone know what is thought process/rule around creating a new Class - when to extend a ‘base’ class and get a subclass or
    create a new class with the ‘base’ class as a member (aggregation?) ?
  2. a good book recommended for object oriented design?

To the authors: great book - approachable and practical.


#2

The standard answer to the question is “Subclassing is used when one thing ‘is-a’ kind of another.” So, you might subclass Shape and create Circle.

The other part of the standard answer is ‘Composition is used when one thing ‘has-a’ instance of another.’ So, Person might have a phone number instance variable.

For Objective-C programmers there is a special case: 'Don’t subclass class clusters unless you really need to." What is a class cluster? That is too deep for now. For now just know: We almost never subclass NSString, NSArray, NSDictionary, NSDate, NSNumber, or NSValue.

So, for example, some people might argue that a BankAccount is a NSArray of transactions with some other stuff (name, address, creditLimit). Those people might be tempted to subclass NSArray. They would find themselves in a world of misery. It is better that a BankAccount has-a NSArray of transactions.


#3

For now I’ll take away the ideas of “is-a” and “has-a”.
Thank you, that was simpler explanation than the jargon-ridden stuff II’ve been reading.