Subject area - an automated workplace with visualization of technological process.

Imagine that there are several identical devices that have two states: open / closed. This is represented by boolean variables:

bool firstDeviceOpened = x; bool secondDeviceOpened = y; 

There is an enum described like this:

 enum State { STATE_NOTHING_OPENED, STATE_FIRST_OPENED, STATE_SECOND_OPENED, STATE_ALL_OPENED }; 

States can be the following (0 and 1 - "closed" and "open", respectively):

 device1 | device2 | method ----------------------------------------- 0 | 0 | STATE_NOTHING_OPENED 1 | 0 | STATE_FIRST_OPENED 0 | 1 | STATE_SECOND_OPENED 1 | 1 | STATE_ALL_OPENED 

Having all this, it is necessary to initialize the state variable with the current state. In the project, these initializations are implemented like this:

 State currentState = STATE_NOTHING_OPENED; if (firstDeviceOpened && !secondDeviceOpened) { currentState = STATE_FIRST_OPENED; } if (!firstDeviceOpened && secondDeviceOpened) { currentState = STATE_SECOND_OPENED; } if (firstDeviceOpened && secondDeviceOpened) { currentState = STATE_ALL_OPENED; } ... // где-то дальше сидит switch, который по состоянию запускает // методы, отображающие смену состояния на визуализации 

Actually the problem is that when adding another device you need to fence a lot of conditions. As a result, it is somehow sad to support 2 N conditions, where N is the number of devices.

Another stick in the wheels puts the situation when there are devices that work in " special cases ", for example:

 // если оба закрыты, открывается третье устройство bool thirdDeviceOpened = !(firstDeviceOpened || secondDeviceOpened); 

How to get rid of the need to fence a bunch of if and handle states for each separate combination?

  • Well, the table will also not be easy to maintain - Komdosh
  • Well, if the truth table is input, then why do you need all these if ? take and see the value from the table for one action - VTT
  • @VTT, do not quite understand what you mean ... Can you give a small example? - Bogdan

1 answer 1

Use bit flags:

 enum State : uint32_t { STATE_NOTHING_OPENED = 0x00 STATE_FIRST_OPENED = 0x01, STATE_SECOND_OPENED = 0x02, STATE_THIRD_OPENED = 0x04, STATE_ALL_OPENED = STATE_NOTHING_OPENED|STATE_FIRST_OPENED|STATE_THIRD_OPENED } // .. uint32_t state=0; if (firstDeviceOpened ) {state |= STATE_FIRST_OPENED ; } if (secondDeviceOpened) {state |= STATE_SECOND_OPENED; } if (thirdDeviceOpened ) {state |= THIRD_SECOND_OPENED; } // .. if (state & STATE_ALL_OPENED) { showMessage ("Взрыв реактора неизбежен! Покайтесь в грехах!"); runAlarm (); pray (); }