bchavez / Bogus

:card_index: A simple fake data generator for C#, F#, and VB.NET. Based on and ported from the famed faker.js.
Other
8.51k stars 483 forks source link

Add ability to except random numbers #512

Closed acnicholls-kroll closed 7 months ago

acnicholls-kroll commented 7 months ago

Please describe why you are requesting a feature

we have a lookups table where the PK is the integer value with a string field. Some records have been removed, meaning the PK values are not 100% sequential. When using randomized data from BOGUS, we sometimes cannot insert that data into a related table with an FK field because the random number is one where the corresponding PK value is missing.

Can you create an extension that would allow us to designate values that would not be preferred within the range of valid random values?

Please provide a code example of what you are trying to achieve

var faker = new Faker();
faker.Random.Number(1,100).Except(92, 34, 85);

Please answer any or all of the questions below

If the feature request is approved, would you be willing to submit a PR?

Yes

bchavez commented 7 months ago

Hi @acnicholls-kroll, this is a bit of a tricky request;

The reason Bogus doesn't support this out of the box is that this scenario can present a few problems:

For example, to create a custom extension method for the Randomizer instance:

void Main()
{
   var faker = new Faker();
   var result = faker.Random.NumberWithExclusion(1,4, except: [1, 2, 3]);
   result.Dump();
}

public static class MyBogusExtensions
{
   public static int NumberWithExclusion(this Randomizer random, int min, int max, int[] except)
   {
      int result = 0;
      do
      {
         result = random.Number(min, max);
      }
      while( except.Contains(result) );

      return result;
   }
}

Notice, we need to re-generate the random.Number() when the generated value is in exclusion. And this kind of code inside Bogus makes it extremely difficult to debug a deterministic sequence because we could potentially pull more values from the seeded sequence rather than just one time.

So in summary, I try to avoid adding "try again" code in Bogus because it makes deterministic debugging more difficult.

But nothing prevents you from adding the extension method above to your code base.

I'll keep it in mind for future enhancement (if I continue to get more requests like this), but for now, I'll try to avoid adding code like this to the main codebase.

acnicholls-kroll commented 7 months ago

many thanks for the detailed response. Will look at adding this extension to our code where we need it.