J
jsguru72
I have a general question about best practices.
I think it would be best to use an example. Basic class to represent
a square.
public class Square {
int length;
int width;
//getters and setters
}
Now, let's say I wanted to add a method to obtain the area of the
square.
I have 2 options.
1) I could calculate it on the fly each time the area is requested.
int getArea() {
return (length * width);
}
2) I could calculate it whenever the length or width change, store the
value, and just return the stored value when requested.
int area;
void setLength(int length) {
this.length = length;
this.area = (this.length * width);
}
Method 1 is more streamlined coding, but requires a calculation be
performed each time the value is requested. Method 2 is a bit more
bulky, but saves having to do the calculation each time I need the
area.
Ignoring factors such as how often the input values would change or
how complicated the the calculation is, is there a best practice
baseline where one method is preferred over the other?
Thanks.
I think it would be best to use an example. Basic class to represent
a square.
public class Square {
int length;
int width;
//getters and setters
}
Now, let's say I wanted to add a method to obtain the area of the
square.
I have 2 options.
1) I could calculate it on the fly each time the area is requested.
int getArea() {
return (length * width);
}
2) I could calculate it whenever the length or width change, store the
value, and just return the stored value when requested.
int area;
void setLength(int length) {
this.length = length;
this.area = (this.length * width);
}
Method 1 is more streamlined coding, but requires a calculation be
performed each time the value is requested. Method 2 is a bit more
bulky, but saves having to do the calculation each time I need the
area.
Ignoring factors such as how often the input values would change or
how complicated the the calculation is, is there a best practice
baseline where one method is preferred over the other?
Thanks.