0

I have my own simple Timer implementation, when a timer is created it register itself at a TimerHandler,

Timer::Timer()
: tick_counter_(0),
  target_tick_(0),
  increment_(false),
  started_(false),
  elapsed_(false) {
  handlers::TimerHandler::RegisterTimer(*this);
}

The function RegisterTimer() is static as you can see and TimerHandler is implemented as a singleton.

As you all known this creates problems at unit testing! Testing the Timer class and the TimerHandler class can be ok and not really hard. But when testing other classes which uses Timer it sometimes become tricky.

I want to get some ideas of how to solve this problem using another kind of design.

My only solution I have come up with currently is to use simple dependency injection by simply passing TimerHandleras an argument everywhere I want to use a Timer. But this will clutter my code badly so I hope to be able to avoid this!

Jepsson
  • 35
  • 1
  • 6
  • 1
    I think those are basically your options. Either you can only have one, or you can have more than one and then you need to pass it everywhere so you know which one to use. – user253751 Oct 30 '19 at 13:43
  • Why is it tricky when using other classes ? – linSESH Oct 30 '19 at 13:58

1 Answers1

0

I think your conclusion is the right one, but it doesn't have to be clutter. This answer describes it better than I can: How to avoid Dependency Injection constructor madness?

parktomatomi
  • 3,851
  • 1
  • 14
  • 18
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Lorenzo Isidori Oct 31 '19 at 11:37
  • Maybe I will have to go with this approach. I am also trying to fulfill the google C++ style guide and it while not work with the pattern I already have. see [this](https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables) for more info. – Jepsson Nov 04 '19 at 08:17