views:

109

answers:

4

I have a bunch of related constants that are not identical. What's the better way to name them?

way #1

kWalkSpeed
kRunSpeed
kEatSpeed
kDrinkSpeed

Or,

way #2

kSpeedWalk
kSpeedRun
kSpeedEat
kSpeedDrink

If we evaluate these based on

  • readability
  • understandability
  • organization in member list (autocomplete)
  • not bug prone with subtle errors due to using wrong variable name

I think way #1 wins readability, they tie for understandability, way #2 wins for organization in autocomplete list, and way #1 also wins for not bug prone.

I'm not sure how often it happens to others, but when variable names like this get long, then its easy to write kSpeedEatingWhenInAHurry when you really meant kSpeedEatingWhenInHome, especially when using autocomplete.

Any perspectives?

+9  A: 

If it comes down to one or the other, I will always do option #1. kSpeedWalk sounds like it should be a boolean, not a value (e.g. am I speed walking, or walking normally).

Matthew Jones
Exactly this. The first set are nouns, the second set are verbs. Seems to convey the wrong intent, to me. Speed drinking, on the house!
tzaman
Speed walking is actually an [Olympic sport](http://en.wikipedia.org/wiki/Speed_walking). Speed programming… alas, not.
Donal Fellows
Absolutely #1. #2 trips my 'quick-reading' ability up.
Paul Nathan
+1  A: 

I prefer kSpeedWalk. It's more consistent IMO. You refer to obj.x, obj.y. x.obj makes no sense! The left most term should be the group of which all the right hand terms fit in to.

Another option is kSpeed_walk, where the underscores act similar to dot notation. But that's not a widely used notation AFAIK, which may lead to confusion for anybody trying to use/add on to your code.

But really, the most important thing is just to not mix them.

Wallacoloo
+3  A: 

One way I've handled this in the past is to namespace the constants, so you have (of course, using your preferred method of capitalization):

Speed.walk
Speed.run
Speed.eat
Speed.drink

or

Speed::walk
Speed::run
Speed::eat
Speed::drink

(Or those might be KSpeed -- I'm not sure what the k in your example is for.)

pkh
The k is for "konstant"
Stephen P
+1  A: 

Are the variables based on the verb, e.g. you're speed walking, or describing a property of the action you're doing?

If you're talking about the speed you're walking, it's usually WALKSPEED, WalkSpeed, walkSpeed (which ever case matches your language of choice).

To name it speedWalk will tell the next English-language speaking programmer who reviews your code that you're dealing with some kind of speed-walking simulation, and eating competition.

Chris S