I have a function in my program that generates random strings.
func randString(s []rune, l int) string
s
is a slice of runes containing the possible characters in the string. I pass in a rune slice of both capital and lowercase alphabetic characters. l
determines the length of the string. This works great. But I also need to generate random hex strings for html color codes.
It seems all sources say that it's good programming practice to reuse code. So I made another []rune
that held [1-9a-f]
and feed that into randString
. That was before I realized that the stdlib already inclues formatting verbs for int types that suit me perfectly.
In practice, is it better to reuse my randString
function or code a separate (more efficient) function? I would generate a single random int and Sprintf it rather than having to loop and generate 6 random ints which randString
does.
Because:
As a side note: this question is exactly about the function you're trying to create: How to generate a random string of a fixed length in golang? I've presented mutiple very efficient solutions.
This is fairly subjective and not go-specific but I think you shouldn't reuse code just for the sake of reuse. The more code you reuse the more dependencies you create between different parts of your app and as result it becomes more difficult to maintain and modify. Easy to understand and modify code is much more important especially if you work in a team.
For your particular example I would do the following.
If a random color is generated only once in your package/application then using fmt.Sprintf("#%06x", rand.Intn(256*256*256))
is perfectly fine (as suggested by Dave C).
If random colors are generated in multiple places I would create function func randColor() string
and call it. Note that now you can optimize randColor
implementation however you like without changing the rest of the code. For example you could have implemented randColor
using randString
initially and then switched to a more efficient implementation later.