Loose coupling keeps related classes useful together without making them depend heavily on one another’s implementation details. This separation improves maintainability because changing one class is less likely to require changes elsewhere. section 9.5.3 section 9.5.4
Use these design practices when connecting related classes:
- Give each class a distinct concern, such as storing account data separately from demographic data. section 9.5.3
- Let callers use the specialized class directly instead of adding forwarding methods to another class. section 9.5.3
- Review class relationships throughout development; use flatter models when inheritance creates dependencies that make updates difficult. section 8.5.5 section 9.5.4
Listing 9.10 Separating classes to have distinct concerns
class Account:
def __init__(self, student_id):
# query the database to get additional information using student_id
self.account_number = 123456
self.balance = 100
class Demographics:
def __init__(self, student_id):
# query the database to get additional information using student_id
self.age = 12
self.gender = "Female"
self.race = "Black"
class Student:
def __init__(self, first_name, last_name, student_id):
self.first_name = first_name
self.last_name = last_name
self.student_id = student_id
self.account = Account(self.student_id)
self.demographics = Demographics(self.student_id)
Inspect a Python design that keeps Account, Demographics, and Student as separate classes while composing the specialized objects inside Student. section 9.5.3
Student data model
A Student object can contain Account and Demographics objects, while callers read account balance or demographic attributes from those specialized objects. Adding database retrieval methods inside Account or Demographics then avoids placing their implementation details in Student. section 9.5.3
















