65.9K
CodeProject is changing. Read more.
Home

Removing Ugly Flags in C++

starIconstarIconstarIconstarIconemptyStarIcon

4.00/5 (11 votes)

Oct 14, 2011

CPOL
viewsIcon

67701

Using the Call Gate idiom to reduce number of boolean flags and state variables.

Let's consider a typical use case.
struct car
{
  car()
    :started_(false)
  {
  }
  ~car()
  {
    stop();
  }

  void start()
  {
    if(started_)
       return;
    do_start();
    started_=true;
  }
  void stop()
  {
    if(!started_)
       return;
    do_stop();
    started_=false;
  }
private:
  bool started_;

  // do actual work
  void do_start();
  void do_stop();
};
Doesn't the 'started_' flag look ugly? It does to me. With the Call Gate idiom, that could be changed to:
struct car
{
  car()
    :start_( boost::bind(&car::do_play, get_this()) )
    ,stop_( boost::bind(&car::do_stop, get_this()) )
  {
    //wire the gates
    start_.wire_on(stop_); //'start' opens the 'stop' gate
    stop_.wire_on(start_); //'stop' opens the 'start' gate
  }
  ~car()
  {
    stop();
  }

  void start()
  {
    start_();
  }
  void stop()
  {
    stop_();
  }

private:
  gate start_;
  gate stop_;

  car* get_this() { return this; }

  // do actual work
  void do_start();
  void do_stop();
};
Replacing only one bool with call gates is probably an overkill, but there is a more interesting sample in Call Gate Idiom, and an actual implementation of the call gates.