Refactoring Arr::random code
#54889
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Hello there,
I was reviewing the code of the
Arr::randommethod when I noticed an issue.The current code of this method is as follows:
The issue is, why should the value of
$numberbe set tonull? Moreover, why should we call this method without specifying how many random values we need?This has resulted in repeatedly checking whether the value of
$numberis equal to null or not.(Four times)Is there any reason other than determining whether we can retrieve the number of random values we need from the input array?
And as mentioned in the documentation of the
pickArrayKeysmethod, the value of$numbermust be at least equal to1.So, if we set the default value of
$numberto1, there will no longer be a need to check it in the first line.And similarly, I observed in the tests of this method:
Why should we call this method and request
0random values?All of these have led to the existence of unnecessary
ifconditions.Therefore, I will refactor this method in the following way:
Here, with just one condition, we can determine that the array is not empty and we can retrieve random values equal to the
$numberparameter.Note: If it is important to you that when
$numberequals1, the value itself is returned rather than an array, this can be handled with a singleifcondition.What is your opinion?
Thank you.
Beta Was this translation helpful? Give feedback.
All reactions