Software Engineering
naming variables
Updated Tue, 24 May 2022 23:20:21 GMT

How to name a variable when the word is both a noun and a verb


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.




Solution

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.





Comments (3)

  • +2 – Excellent point on the units. Units are explicitly left off in this case because they can change depending upon the analysis we're running. Ie, we're using different time scales and the Battery adjusts its operations in terms of the analysis' scale. — Jan 25, 2013 at 20:10  
  • +1 – I prefer verbs for expensive, non-mutating functions. E.g., functions that run a query on a database. — Mar 08, 2013 at 21:55  
  • +0 – Another case where charge not having any units would make sense would be if it returned a value object of Charge type. That could have functions on it like inColoumbs, inAmpHours, inMilliAmpHours that would each return floats. — Oct 10, 2021 at 22:36