Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to name variables with units? [closed]

Tags:

java

variables

Example:

public class Person {
    private String name;

    public String getName(){
        return name;
    }
}

This would lead to something like String name = person.getName();
This is straight forward and I know what kind of variable this is.

But what about:

public class MovingObject{
    private int mass;

    public int getMass(){
        return mass;
    }
}

This leads to int massOfMovingobject = object.getMass();

Question: How can I add the unit to the code so I actually know what I am dealing with ? Should I name it like massInKg, even though it doesn't look good ? One idea would be to add it to documentation but what about the case when it's a global variable within a class ?

like image 241
SklogW Avatar asked May 11 '16 08:05

SklogW


1 Answers

The easiest solution is to store the variable in one unit which is the same to all object for example in your case in Kilogram and then add methods to retrieve different units:

public class MovingObject{
    private int mass; //in KG

    public int getMassinKG(){
        return mass;
    }
    public int getMassinPound(){
        //do the calculation
    }
}
like image 64
Pooya Avatar answered Oct 18 '22 11:10

Pooya