简体   繁体   中英

Should I prefer a const function?

Assume I want to implement class A which must load its "configuration" from a file. And let's assume the "configuration" is a simple map<string, string> .

I can implement the A::LoadConfiguration in two different ways:

  1. void A::LoadConfiguration(string filename)
  2. map<string, string> A::LoadConfiguration(string filename) const

Should I prefer either of the two implementations, and why?

If you prefer the second version when the user wants to get info on a file they will base all their algorithms on the map. If you do the second version, meaning the implementation may be a map, but doesn't have to be , they can base their code around an API which does not have to change even if the internal implementation does.

Consider the situation where later you realize it is far more efficient to use an std array, for whatever reason, now every program using this code has to change many of it's algorithms. Using the first version the change to array can be handled internally and reflect no changes on the outside.

Now if you are planning to make multiple instances of the class you will definitely want to make it a static method because you don't want the file to load every time you call the constructor (especially if the file will not change).

Completely ignoring your suggestions, but this is probably how I would do it (not knowing all your constraints, so ignore me if it does not fit):

class A
{
public:
    static A fromConfiguration( string fileName );

    /* ... */
}

In most cases, the "configuration" of a class should be set at object creation, so forcing the user to provide it on construction is a good thing (instead of having to remember to do do the loading later).

namespace NeatStuff
{
    map<string,string> loadSimpleConfiguration( string fileName );
}

If the configuration file format is really simple (and not specific to your class) you can move the actual loading out of the class.

Assuming other classes use the configuration later, I prefer option 1, and an additional GetConfigurationParameter public const method that gets the config value for a particular key. That lets me make other classes which can just ask for some parameter by name without ever caring that it's implemented as a map.

Another reason why I prefer option 1 is that loading a configuration should be distinct from returning it. If I see a name like LoadConfiguration , I assume that it loads the config from somewhere and sets the parameters in the class. I do not assume it returns some description of the configuration, which I'd instead expect from a method like GetConfiguration - but opinions on this will vary for different people of course.

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