Refactoring a data class in C ++

So, I have the following class that I think is stupid and would like to refactor.

class Data
{
  public:
    bool getVariableA();
    bool getVariableB();
    bool getVariableC();

    void setVariableA();
    void setVariableB();
    void setVariableC();

  private:
    bool A;
    bool B;
    bool C;
}

      

This continues as 100 variables and grows, most of which are booleans. If you reformed this class (while keeping all the data in it instead of propagating), how would you do it?

The problems with the current structure are at least the following: a) too much code; b) pain to add material; c) When testing, coverage should always be added manually as the class grows.

+3


source to share


2 answers


how would you do it?

The solution suggested by @JohnHenly is in place:

I would use this code:



std::vector<bool> data;
enum index { var_a, var_b, var_c, ... };

data[var_a] = true;

      

If possible, consider also splitting the data according to one of the following criteria:

  • logical group
  • where are they used
  • purpose
+3


source


You must first rethink your class. Your class should have a single responsibility in accordance with best practice. Therefore, if you have many member variables, your class can handle more than one responsibility. For refactoring, you can extract more classes from this class. This means that you can group related variables and functionality into another class and use it. For example, if there are variables like

bool isNetworkConnected;
bool isNetworkReachable;
int networkSpeed;
string networkName;

      

In this case, you can create a new class named NetworkInformation

and then declare one class variable, for example



NetworkInformation networkInfo;

      

Hope this helps.

+2


source







All Articles