简体   繁体   中英

Refactoring a data class in C++

So I have the following class which I find silly 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 goes on for like 100 variables and growing, most of which are boolean. If you were to refactor this class (while keeping all the data in it instead of spreading out), how would you go about it?

Issues with the current structure are at least that it's a) too much code b) pain to add stuff c) unit testing coverage always needs to be added manually when growing the class.

how would you go about it?

The solution proposed by @JohnHenly is spot-on:

I would use this code:

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

data[var_a] = true;

If possible though, consider also splitting the data by one of these criteria:

  • logical group
  • location where they are used
  • purpose

First you must rethink your class design. Your class should have single responsibility as per the best practices. So if you have lots of member variables then your class might be handling more than one responsibility. For refactoring you can extract more classes from this class. This means you can group related variables and functionality into another class and use it. For example if have some variables like,

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

In this case you can create a new class named NetworkInformation and then declare a single class variable like,

NetworkInformation networkInfo;

I hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM