Representing your states as bitmask like you write, you can just translate your descriptions of the constraints into code:
if ( (state & HOT) && (state & COLD) ) {
state &= ~HOT;
state &= ~COLD; // reset both HOT and COLD flags if both are set
}
if ( (state & COLD) && (state & WET) ) {
state &= ~WET; // cold items can't be wet
state |= FROZEN; // instead, they're frozen
}
if ( (state & HOT) && (state & WET) ) {
state &= ~WET; // hot and wet items dry up...
state &= ~HOT; // ...and cool down
}
// add other constraints here...
You could wrap that into an makeStateConsistent()
that you can call before testing the state bits to ensure that the state makes sense.
However, one limitation of this approach is that it can't account for the order of state changes. For example, if you want to have a different outcome for hot items that become wet than for wet items that become hot, you can't do it like this: all the makeStateConsistent()
method sees is a hot and wet object, with no information about how it got to be that way.
Instead, what you could do is make the item state private (at least conceptually) and manipulate it through a set of methods like coolItem()
, heatItem()
, wetItem()
, dryItem()
and so on. That way, the state change methods themselves can take care of any additional changes. For example, the heatItem()
method might look something like this:
if ( state & COLD ) {
state &= ~COLD; // cold items become normal temp when heated
if ( state & FROZEN ) {
state &= ~FROZEN; // ...and melt if they were frozen
state |= WET;
}
} else if ( state & WET ) {
state &= ~WET; // wet items dry up when heated, stay normal temp
} else {
state |= HOT; // dry normal temp items become hot
}
Of course, you may still want to also have a makeStateConsistent()
method as a backup, just in case you have a bug in your state change methods.
Also, in some cases you may be able to simplify your code by eliminating unnecessary states. For example, do you really need a separate FROZEN
state, or would it be enough to just treat any cold and wet items as frozen?