Why is creating dependencies with new inside a class considered a problem?
It hard-wires the class to one concrete implementation, hides what it depends on, and makes it impossible to replace in tests or in other environments without editing the class.
Explain it simply
If a caterer's recipe says "buy vegetables from Ramesh's shop at the corner", the caterer cannot work when that shop is shut and cannot try a cheaper supplier. A recipe that says "get vegetables" can be served by any shop.
Example
# Problem: the class chooses its own database
class ReportService:
def __init__(self):
self.db = MySqlDatabase("prod-server") # hard-wired
def monthly(self):
return self.db.query("SELECT ...")
# Better: it just asks for something that can query
class ReportService2:
def __init__(self, db):
self.db = db
def monthly(self):
return self.db.query("SELECT ...")
ReportService2(InMemoryDatabase()).monthly() # test
ReportService2(MySqlDatabase("prod-server")).monthly() # productionUsing new for plain values and small helpers such as new ArrayList<>() or a Point is fine. The problem is with collaborators that reach outside or have behaviour you may want to swap.
What to say in the interview
"Instantiating collaborators inside a class couples it to a specific implementation, hides the dependency and blocks testing. I pass them in instead, and I reserve new for simple values and objects whose type will never vary."
Common mistakes
- Believing every new keyword must be removed.