KhDonen
KhDonen

Reputation: 289

How to handle class visibility/access correctly

I'm designing a simple game and I'm not sure how to correctly handle the access and relations between classes. E.g:

Class Game - method Start that will initialiaze objects (fields) Player, CPUPlayer, Board.

Player/CPUPlayer contains a method "Place a pawn" but they would need to access the Board object to check for coordinates.

But they do not see the Board object. Does it mean I need to pass the Board object reference (or any other objects) in their constructor?

Upvotes: 0

Views: 48

Answers (2)

Max Yankov
Max Yankov

Reputation: 13327

In this particular case, it does indeed seem that they need a reference to a Board object. If you would like to over-engineer that, you could create a specialized interface ICoordinateCheckable, implement it in the Board, and have Player accept an instance of this interface (instead of the Board) in constructor.

Upvotes: 0

Mike Perrenoud
Mike Perrenoud

Reputation: 67918

Yes, if they have a dependency on that object you need to inject it into them when they are created. The constructor is the right place. Later on, as you get a handle on things, you may want to look into using a DI container like Unity or something, but for now, just receive an instance of the Board in their constructors.

Upvotes: 1

Related Questions