From the documentation:
Do not combine the call to Randomize in a loop with calls to the Random function. Typically, Randomize is called only once, before all calls to Random.
(Highlighting of 'only once' by me)
Best practices question:
if a Delphi library uses Random
, should it only document the requirement of the initializing call of Randomize
, and leave the call of Randomize to the user of the library?
Or should the library take care of the initialization, like
if System.RandSeed = 0 then Randomize;
In my humble opinion it totally depends on the structure and purpose of your library.
If the user will never see the Random calls, then I would suggest to make the library initialize it always. Putting it in the docs would not be necessary.
On the other hand, if the user actually directly calls Random or some wrapper of it by using your library (which I guess is how your library works), then the user will (should) be aware that he is using some sort of random-generating function that will require an initialization, since the Random sequences in most languages are really pseudo-random sequences based on a seed.
It might be that the user requires the random sequence to be initialized several times, or maybe he/she will be happy with initializing it just once. It totally depends on the user needs.
I would not force it but rather make the Randomize call available to the user, and maybe give the user the possibility of telling the library to either take care of the initialization or leave it to him/her. And in this case all should be documented.
HTH
If you're not sure, just always call randomize().
It's better to have code rely on the fact that it's called than on the fact that it's not called.
That's because random
and randomize
are global to your application, and you can't know for sure if some other unit or piece of code calls randomize() at some point.
It's convenient to have these global functions, but it's not really a clean design. A TRandomizer class is probably better, where you can set the seed for a certain scope, without affecting the rest of the application.
I guess that this is some leftover from the DOS days.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With