Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If a Delphi library uses Random, should it avoid to call Randomize itself?

Tags:

random

delphi

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;
like image 363
mjn Avatar asked Feb 21 '23 01:02

mjn


2 Answers

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

like image 165
Guillem Vicens Avatar answered May 06 '23 12:05

Guillem Vicens


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.

like image 43
Wouter van Nifterick Avatar answered May 06 '23 12:05

Wouter van Nifterick