My real object comes from combinatorics but here I will use simpler example. Suppose we have bunch of classes and algoritms that iterate through prime numbers (2,3,5,7 - up to several million numbers). Generating prime numbers is expensive so it's natural to precalculate them and save in file:
typedef unsigned long long PrimeType;
const unsigned long PrecalcPrimesNum = 10000000; //here it's arbitrary but in my case size of the object is also mathematically predefined.
vector<PrimeType> calcFirstNPrimes(); //generate them somehow
savePrimes(const string& filename, const vector<PrimeType>& primes);
vector<PrimeType> loadPrimes(const string& filename){
//possible exceptions is important.
vector result; result.resize(PrecalcPrimesNum); //potential exception here...
ifstream ifs(filename);
if(!ifs || check_file_consistency) throw runtime_error("no or wrong file!");//...and here
//load data to result somehow
return result;
}
Now what is preferred pattern for loading and using this data? Below are some patterns I could think of.
Dependency injection:
class FirstNPrimes {
vector<PrimeType> primes;
public:
FirstNPrimes(const string& filename); //load primes or throw exception
const vector<PrimeType>& getPrimes() const {return primes;}
};
...and then pass this object to any class that might use it. This looks silly for me, because FirstNPrimes is not a resource or dependency - it's mathematical constant! You wouldn't use dependency injection for number pi, would you?
Alternative to dependency injection is class with static method getPrimes() (are globally accessible constants ok?) - but then when to load the data? Lazy initialization means that any call to getPrimes() becomes the source of potential exception from loadPrimes. It's possible to emulate static constructor as described here, but then how to output the cause of exception?
So for now I think about requiring explicit call to loadPrimes (i.e. in the beginning of main()), and adding assertion to getPrimes. But this also doesn't look ideal.
Is there a common pattern which I didn't think of?
Aucun commentaire:
Enregistrer un commentaire