Should units of measurement always be included in all the variable names?

Belphegor :

I've seen some differing views on whether or not you should include the units of measurements in variables and I'm not quite sure how to deal with corner cases.

For example if I had a variable that stored the "acceleration" obtained from an accelerometer would I have to explicitly state in the variable name its units of measurement which is meters per second squared?

Double acceleration; // m/s^2
// or this
Double accelerationMetersPerSecondSquared
// or maybe this
Double accelerationMeterPerSecSqr

As you can see, my concern is that the variable name can become quite long if the units of measurement are complex and if it's something like acceleration which is known to be in the units of m/s^2 is it necessary to have it?

Of course in other cases it is necessary to have units of measurement such as having a variable to store time.

int time; // time in what unit??
// this is more clear
int timeInSeconds;
GhostCat salutes Monica C. :

At least for the second part, the latest updates for the Java "date time" APIs have a simple answer.

int time; // time in what unit??

turns into:

Duration somePeriodOfTime ...

That probably tell us what the ideal solution for the first examples could be: to define distinct types, too. So don't use a double that represents square somethings.

Create a class (ideally with "value" semantics) like Area that always contains a numerical value (maybe a double) together with its unit.

That unit could then be implemented as enum, and then you nicely add some built-in conversion code that does the square feet to quadrat meter thing almost magically.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=122885&siteId=1