When and why to subclass

This chapter has introduced you to class inheritance, along with the numerous programming techniques that subclassing enables.

But you might be asking, “When should I subclass?”

Rarely is there a right or wrong answer to that important question, but understanding the trade-offs can help you make the best decision for any particular case.

Using the Student and StudentAthlete classes as an example, you might decide you can simply put all of the characteristics of StudentAthlete into Student:

class Student: Person { var grades: [Grade] var sports: [Sport]

//…

}

In reality, this could solve all of the use cases for your needs. A Student that doesn’t play sports would simply have an empty sports array, and you would avoid some of the added complexities of subclassing.

results matching ""

    No results matching ""