Reputation: 135
I have got the following question which is pondering me for some time. I'm new to state machine modeling so would really appreciate your help, ideas, and suggestions.
Let's say I have a "Valve" which can be in state "opened" or "closed". Now when I model the state machine.
Should I define two booleans for each state?
bool opened;
bool closed;
Hence, I should use both booleans for each state?
Example: State "opened" will have the booleans--> opened = 1 and closed = 0;
OR
Simply can I define only one boolean variable?
bool opened;
Example: State "opened" will have only one boolean-->opened = 1 and in the state "closed" it will have boolean opened = 0;
What is the best practice here? Any advantages of using two booleans over one boolean? I can imagine in this case too many variables have to been defined and reset every time state transitions into another state.
Thank you in advance
Upvotes: 0
Views: 1793
Reputation: 305
I think you could consider not using boolean at all to represent object state. Most objects will have more than two states, and if you use boolean flags you'll end up with qute a lot of them. This can make it quite hard to test and verify that the code works as expected all the time. I worked with someone who had 22 boolean flags in one class. This meant that the class has over 4 million possible states.
I usually use an enum to represent class state. The Valve could be Open or Closed, but what if it became defective, and impossible to operated? I can easily add more states to the enum increasing the number of states by 1, but if I use an boolean I will exponentially increase the number of possible states when adding more flags.
I'd also recommend using a state machine library, instead of manually handling state in your own code. There are many state machine libraries available, I use (and contribute to) the stateless state machine library on Github.
Upvotes: 1
Reputation: 62106
If the two states are mutually exclusive, there's no point in having a redundant state variable, which you'd need to maintain. A single boolean provides you with two possible states already.
Depending on the language, you might be able to introduce an alias such that you'd be able to refer to the same state under different names, purely for aesthetic purposes, and the compiler would remove the redundancy. But again, it may be more of a nuisance than something truly useful.
You want to have additional state variables when you need to deal with independent states or when you want to describe substates.
Upvotes: 0