Refactoring Arr::random
code
#54889
Unanswered
alirezasalehizadeh
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Hello there,
I was reviewing the code of the
Arr::random
method when I noticed an issue.The current code of this method is as follows:
The issue is, why should the value of
$number
be 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
$number
is 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
pickArrayKeys
method, the value of$number
must be at least equal to1
.So, if we set the default value of
$number
to1
, 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
0
random values?All of these have led to the existence of unnecessary
if
conditions.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
$number
parameter.Note: If it is important to you that when
$number
equals1
, the value itself is returned rather than an array, this can be handled with a singleif
condition.What is your opinion?
Thank you.
Beta Was this translation helpful? Give feedback.
All reactions