Variable Naming – Handling Words That Are Both Nouns and Verbs

namingvariables

I have run into a corner-case problem with the general guidance of:

  • nouns for variables
  • verbs for functions

Specifically, I have a case where the word is ambiguous – it can be either a verb or a noun. And in some cases when we're discussing the application, it will be used both ways in the same sentence.

My intent is to make sure the program will remain readable to future developers as well as myself when I return to sections of code months later.

One of the examples is with a battery. A battery has a charge and you can also charge() a battery.

I think that having both Battery.Charge and Battery.Charge(value) will be confusing to future developers.

My current solution is to simply pick a different word for one or both of those cases (the variable and the function). My problem with that approach is the Battery object's variable and function for charge won't align with design discussions involving the Battery.

My question is if there is another / better way to handle this conflict in naming convention?


Some additional reading on the subject. None really addressed the particular of my question.

Best Answer

In similar situations I try to find synonyms. In this case I would use "recharge" for the verb. The "re-" is slightly redundant, but the meaning is clear. Using the simple "charge" for the remaining charge in the battery is ambiguous because it doesn't specify any physical units. I would prefer "availableAmpHours", "hoursUntilRecharge" or something similar. The units will depend on whatever is convenient for the application.

My personal preference is to use verbs only for functions that change state. I use nouns for non-mutating functions. I suppose it depends on your point of view. At the machine level, non-mutating functions do something, but at the model level, they don't.

Related Topic