I am programming a game in java, and as the question title suggestions i am using public fields in my classes. (for the time being)
From what i have seen public fields are bad and i have some understanding why. (but if someone could clarify why you should not use them, that would be appreciated)
The thing is that also from what i have seen, (and it seems logical) is that using private fields, but using getters and setters to access them is also not good as it defeats the point of using private fields in the first place.
So, my question is, what are the alternatives? or do i really have to use private fields with getters and setters?
For reference here is one of my classes, and some of its methods.
I will elaborate more if needs be.
public double health;
//The player's fields.
public String name;
public double goldCount;
public double maxWeight;
public double currentWeight;
public double maxBackPckSlts;
public double usedBackPckSlts; // The current back pack slots in use
public double maxHealth; // Maximum amount of health
public ArrayList<String> backPack = new ArrayList<String>();
//This method happens when ever the player dynamically takes damage(i.e. when it is not scripted for the player to take damage.
//Parameters will be added to make it dynamic so the player can take any spread of damage.
public void beDamaged(double damage)
{
this.health -= damage;
if (this.health < 0)
{
this.health = 0;
}
}
EDIT: For checking purposes, this is what my Weapon
class looks like now: (Code sample is not working for some reason, so it does not look right.)
private final double DAMAGE;
private final double SPEED;
public Weapon(double initialDmg,double initialSpd,String startName,double initialWg)
{
DAMAGE = initialDmg;
SPEED = initialSpd;
setItemName(startName);
setItemWeight(initialWg);
}
public double getSpeed()
{
return SPEED;
}
public double getDamage()
{
return DAMAGE;
}
As you can see, as the Weapon's
DAMAGE
and SPEED
do not need to be changed, they can be final's for the time being. (if, later in the game, i decided these values can be "Upgraded" so to speak, i may add setters then , with validation, or just make a new weapon with the upgraded values) They get set in the Weapon's
constructor.
Conclusion: getters and setters are fine, as long as they are used smartly, and only used when needed. (however)