Use case
When the user logs in into our website a 6-digit code is generated and sent to the user's email. User is then required to input the code before he is allowed into the protected area. This is basically the same procedure that Steam has when you try to login from a new device/browser.
I've committed the following code, which generates random 6-digits alphanumerical code for the purposes outlined above.
My Code
public static string CreateShortCode(int size = 6)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
var guid = Create();
var result = new StringBuilder(size);
foreach (var b in guid.ToByteArray().Take(size))
{
result.Append(chars[b % chars.Length]);
}
return result.ToString();
}
A senior programmer has changed my code to the following:
Code after code-review
public static string CreateShortCode(int size = 6)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890".ToCharArray();
var maxRandomValue = (256 / chars.Length) * chars.Length;
var result = new StringBuilder(size);
while (result.Length < size)
{
var data = new byte[size];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(data);
}
foreach (var b in data)
{
if (b > maxRandomValue)
{
continue;
}
result.Append(chars[b % chars.Length]);
}
}
return result.ToString();
}
Can you please explain how his code is better?
Aucun commentaire:
Enregistrer un commentaire