4

I have a module or class Random and in it there's a method called generate(). A client will always call it as res = Random.generate(). And from the inside, obviously, it can be called simply as generate().

What'll be a good choise: leave its name as is, or rename it to generate_random()? What's the most common practise in such situations?

2
  • 3
    It's generally acceptable to tailor the method name to the namespace it is found within. Otherwise it would be pointless to have different namespaces.
    – Steve
    Sep 3, 2020 at 13:24
  • It depends. I would generally agree with @Steve in that you don't need to repeat the namespace, but the method name should also be sufficiently descriptive. Some well-known cases like Random might be self-explanatory, but I would err on the side of over-explaining. The last random generator method I wrote was for strings, not numbers as is usually the case.
    – Dan Wilson
    Sep 3, 2020 at 15:03

2 Answers 2

7

It's about context.

generate() is fully descriptive of "generate random" when in the context of random. So this isn't about being descriptive. This is about being self contextualizing.

The need to be self contextualizing stems from one thing: taking the method out of context. If you never do that there is no need to be self contextualizing.

The common practise is to read things within their context and name them as such. Conversely, when taking them out of their context it's typical to rename them.

1

Most random number libraries I know take care of this issue by naming the baseline random number generating method Random.random() or Random.rand(). This is unambiguous both if you have the class/module name as context (although slightly repetitive), as well as in isolation.

This is probably because random number libraries are used quite often and so you want it to be unambiguous in all contexts.

This naming scheme is not always universally applied though. Consider e.g. Python, where you have random.random and random.randrange, but then other methods are named random.choice, random.sample, etc. Arguably a function called choice is still sufficiently descriptive, if you do not need to know how the choice is made (namely randomly).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.