So, the quote comes from “Dependency Injection in .NET”. Having that in consideration, is the following class wrongly designed?
class FallingPiece { //depicts the current falling piece in a tetris game
private readonly IPieceGenerator pieceGenerator;
private IPiece currentPiece;
public FallingPiece(IPieceGenerator pieceGenerator) {
this.pieceGenerator = pieceGenerator;
this.currentPiece = pieceGenerator.Generate(); //I'm performing work in the constructor with a dependency!
}
...
}
So this FallingPiece class has the responsibility of controlling the current falling piece in a tetris game. When the piece hits the bottom or some other place, raises an event signaling that and then, through the factory, generates another new piece that starts falling again from above.
The only alternative I see is to have an Initialize() method that would generate the piece, but IMO that goes a bit against the idea of having the constructor put your object in a valid state.
In general, rules of thumbs are exactly that: rules of thumb. Not immutable laws that one should never deviate from — I’m pretty sure you’ll find cases where doing things with your dependencies in your constructor makes more sense than otherwise.
With that in mind, let’s revisit your particular design:
Seems weird to me that
FallingPiecetriggers the piece generator after its finished.I’d design it something like this:
At least with this design, the
GameEngineis fully responsible for telling the Generator when to create its pieces, which seems more idiomatic than the FallingPiece having that duty.