假设我希望有2个函数,一个函数在给定范围内生成一个随机整数,另一个函数在给定范围内生成一个随机双精度数。
int GetRandomNumber( int min, int max );
double GetRandomNumber( double min, double max );
Run Code Online (Sandbox Code Playgroud)
请注意,方法名称相同。我正在尝试决定是命名功能还是...
int GetRandomInteger( int min, int max );
double GetRandomDouble( double min, double max );
Run Code Online (Sandbox Code Playgroud)
第一种选择的好处是用户不必担心他们正在呼叫哪个。他们可以只使用整数或双精度值调用GetRandomNumber并获得结果。
The second option is more explicit in the names, but it reveals unneeded information to the caller.
I know this is petty, but I care about petty things.
Edit: How would C++ behave regarding implicit conversion.
Example:
GetRandomNumber( 1, 1 );
Run Code Online (Sandbox Code Playgroud)
This could be implicitly converted for the GetRandomNumber function for the double version. Obviously I don't want this to occur. Will C++ use the int version before the double version?
我更喜欢你的第二个例子,它很明确,并且在解释上没有任何歧义。最好在方法名称中明确地说明该成员的目的和功能。
您的方法的唯一缺点是您将方法名称与返回类型耦合在一起,如果您想要更改这些方法之一的返回类型,这并不理想。但是在这种情况下,我最好添加一个新方法,并且无论如何都不要破坏 API 中的兼容性。