What are constructor injection and setter injection, and which should you prefer?
Constructor injection passes dependencies when the object is created, so it is never half-built. Setter injection sets them afterwards. Prefer the constructor for required dependencies and setters only for optional ones.
Explain it simply
Buying a scooter with petrol and a key included, versus buying one and then arranging fuel later. With constructor injection, the object arrives ready to use. With setters, someone may forget a step and use it before it is ready.
Example
class Billing {
private final PaymentGateway gateway; // required, can be final
private Logger logger = new NoOpLogger(); // optional, has a safe default
Billing(PaymentGateway gateway) { // constructor injection
this.gateway = Objects.requireNonNull(gateway);
}
void setLogger(Logger logger) { // setter injection
this.logger = logger;
}
}
Billing b = new Billing(new UpiGateway());
b.setLogger(new FileLogger());Constructor injection makes required dependencies visible in one place, supports final fields, and fails fast if something is missing. Too many constructor parameters, say more than four or five, hint that the class does too much.
What to say in the interview
"I use constructor injection for mandatory dependencies, so objects are always valid and immutable, and setter injection only for optional ones with sensible defaults. A long constructor is a hint to split the class."
Common mistakes
- Using setters for everything and ending up with objects that can be used before they are ready.