0

Let's say I have Game class. This game class gets constructed with all its dependencies by Game(ITimer timer, IPointsUpdater updater). When the timer raises Elapsed the updater calculates the user's current points. The timer is stored in a private readonly property in the game class.

Now I want to glue all that together. I have some kind of UI and every time the points are updated I want to refresh my UI. This is how I would do it:

var timer = new Timer(500);
var updater = new Updater();
var game = new Game(timer, updater);

timer.Elapsed += (_,_) => RefreshUi();

Is it okay to subscribe directly to the timer? I have alternatives:

  • I could make the timer property in the game class public. Then I could subscribe to game.Timer.Elapsed directly. That seem against data encapsulation for me since this would allow me to i.e. start/stop the timer, as well.
  • I could let game have an Updated or Elapsed event itself and just forward the Elapsed event from the timer directly. That still leaves my encapsulation intact while having more lines of code to write.

    I prefer my solution utilizing the dependency injection. Is this the best practice? Thanks in advance!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.