7

I was wondering if there was an easier way to increment another class's private variables. Here is how I generally would go about it:

If I only need to do this rarely in my code:

pc.setActionsCurrent(pc.getActionsCurrent()-1);

If I need to do lots of incrementing, I would just make a special setter:

//In the PC class
public void spendAction(){
    this.actionsCurrent--;
}

//In the incrementing Class
pc.spendAction();

Is there a better way to go about this? If the variable were public

pc.actionsCurrent--;

would be enough, and I can't help but feel I'm over-complicating things.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
dGFisher
  • 107
  • 1
  • 8

2 Answers2

2

No. The method abstraction is generally the way to go about it, you might also pass in the increment value (and you can leverage that in your implementation). Consider something like

private long increment = 1;
private long myVariable = 0;
public void setMyVariable(long myVariable) {
    this.myVariable = myVariable;
}
public void setIncrement(long increment) {
    this.increment = increment;
}
public long getMyVariable() {
    return this.myVariable;
}
public void addToMyVariable(long val) {
   this.myVariable += val;
}
public void incrementMyVariable() {
   addToMyVariable(increment);
}

The above would allow the increment value to vary (and this is generally called encapsulation).

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
1

Just define an increment method. For generality you could supply the increment as a parameter, and it could be negative:

public void increment(int augend)
{
    this.actionsCurrent += augend;
}
user207421
  • 305,947
  • 44
  • 307
  • 483