Design – Should an Object Load Itself?

cdesignobject-oriented-design

although I'm programming in C++ for some time now, I'm always faced with design decisions (probably due to the language's flexibility). One such problem is deciding if a method should be part of the class or not.

As an example, oftentimes, I have a Simulation class similar to the following,


class Simulation{
public:
    Simulation(void);
    bool init(const char* init_file){
        //...
        particles_ = read_particles(init_file);
        //etc
    }
    //or even,
    bool init(int argc, char* argv[]);
    void run(void);
private:
    std::vector particles_;
    //Other private members
};

Here, I'm not sure if this init method, which parses a file and initializes the simulation should really be a class method. A different way to implement similar functionality, would be to have an external function or class which handles the parsing of either the command line arguments or the initialization file, and calls appropriate methods of the Simulation class.


bool init_simulation(Simulation& sim, const char* init_file){
    //...
    Particles particles = read_particles(init_file);
    sim.set_particles(particles);
    //etc
}

On the one hand it's easier to implement the functionality as a class method and it avoids having to introduce new classes/structs, specifically for passing parameters. On the other hand, externally handling the initialization, means that one can more easily extend it, although any changes on the Simulation class will propagate to the function.

What is the preferred design in situations similar to the one described above, and how should I approach similar design decisions?

Best Answer

Your problem isnĀ“t having a class with a constructor method, your problem is what you have put into it. Parsing a text file should not be part of the object - its job is to create and manage Simulations. The constructor/init method should take a simple list or map of particles as one of its parameters and use that data when initialising. Reading data from a file and converting it into a simple list or map is the job of some other part of your code.

  • If you change the file format, or completely change how your data is stored (e.g. in a relational database), you should not have to rewrite the Simulation class.
  • You should not need an input file to write tests for this class. Your tests should be able to create simple input data and pass that directly to the object.

Separation of concerns. The file (its location, format etc.) is no concern of your Simulation object.

Related Topic