In some languages where you cannot override 开发者_Go百科the () operator, I have seen methods with a single underscore, usually for 'helper' classes. Something likes this:
class D10
{
public function _()
{
return rand(1,10);
}
}
Is it better to have the function called Roll()? Is a underscore fine? After all, there is only one function, and it removes the need to look up the name of the class.
Any thoughts?
I would say it is a bad style. You can not infer behaviour from the name of the function if it simply an underscore.
In order to know what it does you need to read the code, or documentation.
(On a side note, I don't think D10 is a good name for a class either).
I guess it's a matter of taste. But I don't like it.
I believe having full self-explanatory names is always a better practice.
You won't save much time using only one keystroke to call your function but you'll likely loose more time remembering what it does afterwards.
But again, it is very subjective.
It may be legal, and whoever you're working with might not mind (even more so if you're working alone) but if it were me it would make me crazy. Spelling out D10.roll()
doesn't take up much of your time, and it makes your code that much easier to follow since the name is self-explanatory.
The bottom line, though, is that elegance is in the eye of the beholder; if everyone who's working on your code agrees that that's a simple and clear identifier, nobody is going to stop you.
To me, this is quite obviously bad style.
Method names are names, and are supposed to be descriptive. They're not "proper names" like you have for people*, places and so on, they're names that describe the actions taken by the code contained within.
* Although of course many names for people were almost literally descriptive originally, but that's not generally the indended use nowadays.
I don't think the structure is optimal to begin with. I would simply do this:
class Dice
{
public int D10()
{
return rand(1,10);
}
public int D6()
{
return rand(1,6);
}
// And so on...
}
Then it will be made clear that we're actually taking about dice here and we don't have to create one class for every possible dice.
If you really need to abstract away what dice you're using, I hope that you're using a language that handle functions as first class objects, in which case you would do this:
void RussianRoulette(SOMEFUNCTIONSIGNATURE dice)
{
if (dice() == 1)
print "BANG";
else
print "click";
}
RussionRoulette(Dice.D6); // Regular russian roulette
RussionRoulette(Dice.D100); // For the faint of heart
RussionRoulette(Dice.D1); // Die! :)
精彩评论