Skip to content

Instantly share code, notes, and snippets.

@dishbreak
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dishbreak/9315491 to your computer and use it in GitHub Desktop.
Save dishbreak/9315491 to your computer and use it in GitHub Desktop.
Correction: The Right Way To Manage State in C++
void Television::pressPowerButton()
{
tvIsOn = !tvIsOn;
if (tvIsOn == true)
{
turnOn();
}
else
{
turnOff();
}
}
class Television
{
public:
Television();
~Television();
void pressPowerButton();
private:
bool tvIsOn; //state variable
void turnOn();
void turnOff();
};
Television::Television()
{
//on creation, the television is off.
tvIsOn = false;
}
Television::~Television()
{
}
bool Television::pressPowerButton()
{
//if the current state is on, try to turn off
if (tvIsOn == true)
{
tvIsOn = turnOff();
}
//otherwise, the current state is off, so try to turn on
else
{
tvIsOn = turnOn();
}
//report the current state back to the user
return tvIsOn;
}
bool Television::turnOn()
{
//set a variable for success
bool success = false;
//do stuff to turn on, set success variable accordingly.
//if we succeeded, return the new state of "on".
if (success)
{
return true;
}
//otherwise, keep the state as "off".
else
{
return false;
}
}
bool Television::turnOff()
{
//set a variable for success
bool success = false;
//do stuff to turn off, set success variable
//if we succeeded, return the new state of "off".
if (success)
{
return false;
}
//otherwise, keep the state as "on".
else
{
return true;
}
}
class Television
{
public:
Television();
~Television();
bool pressPowerButton();
private:
bool tvIsOn; //state variable
bool turnOn();
bool turnOff();
};
Television * tv = new Television();
//conditional is true if call to pressPowerButton() is false.
if ( !( tv->pressPowerButton() ) ) {
//alert! We have an issue
}
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment