The class is syntactically valid. It fails only if PostgresDB is unavailable or construction fails; injecting a database dependency also removes the hard-coded implementation.
Fix the error in the following Python class definition:
The class is syntactically valid. It fails only if PostgresDB is unavailable or construction fails; injecting a database dependency also removes the hard-coded implementation.
Короткий ответ
Что ответить на собеседовании
Подробный разбор
Ответ с пояснениями
Условие
Fix the error in the following Python class definition:
class OrderService:
def __init__(self):
self.db = PostgresDB()
Ответ
The class is syntactically valid. It fails only if PostgresDB is unavailable or construction fails; injecting a database dependency also removes the hard-coded implementation.
One possible refactoring is:
class OrderService:
def __init__(self, db):
self.db = db
# At the application composition root:
# service = OrderService(configured_database)
The caller now owns database configuration and connection lifetime, and tests can supply a compatible fake. If the actual error is NameError, importing or defining PostgresDB would address that immediate error, but the snippet does not provide its module. Do not invent an import path or claim dependency injection fixes every connection failure.