Interview Q&A / Object-Oriented Programming

BeginnerQuick answer1 min readUpdated 3 Oct 2026

Why is creating dependencies with new inside a class considered a problem?

SHORT ANSWER

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

python
# 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()  # production

Using 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.

#dependency-injection#coupling#design

Related questions

Practise more Object-Oriented Programming questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Object-Oriented Programming quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.