开发者

c++ Loader class

I was thinking of a loa开发者_如何学Goder class and came up with two different approaches.

class Loader{
public:
  Loader(const Path& path);
  File load() const;

private:
  Path path_;
};

vs

class Loader{
public:
  Loader();
  File load(const Path& path) const;
};

With the first approach, I need one Loader per file and the Loader class represents a state. With the second one, I can load different Files with one loader class. Besides these obvious differences which approach would you choose and why or is there a third maybe superiour way?


There are other approaches as well.

If you don't maintain any state in the Loader class when loading a file, then you can simply write a free function

File load(const Path& path); //a free function.

Or you can make the function static if you want it to be a member function

class Loader{
public:
  static File load(const Path& path);
};

//usage
Loader::load(path);

Sometimes such solutions entirely depend on the situation, and sometimes on company/programmer's personal preferences and taste. There is no one best solution as such!

You can even choose to write the load function in the File class itself:

class File {
public:
  bool load(const Path& path); //non-static, or/and the next one!
  static File load(const Path& path); //static
};

In this, maybe, you would want to change the name of the function: open() seems better than load().


It depends on when the path information becomes known to you. If e.g. you have a Loader member in a class, but do not already know the path when you call that class' constructor you would need to do something like the second approach. If you do know the path already then the first approach might be better.

In general, this is not an one size fits all question.


It is just up to what you need in your application. Do you need the state later? Or pass the initialized loader somewhere else to do the actual load? Then you might need the state. Otherwise not.

There is no general "best" solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜