mtx
mtx

Reputation: 1234

In which situation to declare instance variable?

I have simple class :

class Blah { 

  private PApplet applet; 
  private float value;

  public Blah(PApplet theApplet, theValue) {
    applet = theApplet;
    value = theValue;
  }

  public float getX() {
    return PApplet.map(value, applet.min, applet.max, applet.c1, applet.c2);
  }

}

I wonder now, is it ok to have getX() as described?

Shouldn't I declare a variable xpos and a setter and getter for it? How do I decide whether I should declare an instance variable or not in such situations? (where one instance variable value is dependent on another instance variable)

With an xpos instance variable I would have:

class BlahBla {
  private PApplet applet;
  private float value;
  private float xpos;

  BlahBla(PApplet theApplet, float theValue) {
    applet = theApplet;
    value = theValue;
    xpos = PApplet.map(theValue, applet.min, applet.max, applet.c1, applet.c2);
  }

  public getX() {
    return xpos; 
  }

  public setX(float theValue) {
    xpos = map(theValue, applet.min, applet.max, applet.c1, applet.c2);
  }

}

Advantages to have xpos as instance variable:

Disadvantages to have xpos as instance variable:

Considerations:

Upvotes: 1

Views: 111

Answers (2)

Bohemian
Bohemian

Reputation: 424973

Have only a getter as per your first version: Don't have a field:

  • simpler code
  • don't have to worry about the case where value etc changes in the life of the object (might not happen today, but might happen one day)
  • less code
  • it's premature optimization:

The only reason to store the calculated attribute in a field is "performance", but if you're thinking about it at design time that itself is a big mistake. Only consider using a field if you have hard evidence there actually is a performance problem. Also, if you only call the getter for some objects, it would be a waste to calculate it for all objects.

It is not necessary, or meaningful, to have a setter in either case.

Upvotes: 1

user2137101
user2137101

Reputation:

The main advantage of having a field and a getter is that it will act as a caching system, so that you won't be computing the same value again and again (which can be good as it can be horrible depending on what you are doing). The con is that it will lead to a less clear code and it can consume more memory if your value is big.

To me, you should use a field and a getter (not a setter if the value has not to be changed, remember the open/closed principle), but again it depends on how you are planning to use your class.

Also, yes you can perform operations such as mapping in the setter, that's actually why you should use setters: you disallow direct access to your field so you have a control point over your field modification, which can be used to perform operations on the parameters (like checking them for null values, for example)

Upvotes: 0

Related Questions