Which is a better way to do this, in terms of performance or other factors?
Say I am creating a class with jut one method in it that takes 2 values and adds them together.
Is it better to have 2 instance variables to store the 2 values then have a method which uses these, or is it better to just pass the variables in as parameters when calling the method?
Note: this class is only ever created just to use this method.
public class MyClass {
int value1;
int value2;
public MyClass(int value1, int value2){
this.value1 = value1;
this.value2 = value2;
}
public int MyMethod(){
return value1 + value2;
}
or this way:
public class MyClass {
public MyClass(){
}
public int MyMethod(int value1, int value2){
return value1 + value2;
}
Or would it be better to just use a static method, so I don't need to create an object every time I use the method?
Which is a better way to do this, in terms of performance or other factors?
These ways have no relation with performance. These are way of designing.
The first form (storing the arguments as fields):
public MyClass(int value1, int value2){
this.value1 = value1;
this.value2 = value2;
}
public int myMethod(){
return value1 + value2;
}
makes sense if you want to save the passed information in the class in order to be able to invoke myMethod()
when you want (the creation of the object and the computation may be differed in the time) but also to use value1
and value2
later in another methods of the instance.
The second form (using only the arguments) makes sense if you want only compute the result :
public int myMethod(int value1, int value2){
return value1 + value2;
}
Use one or the other one according to your need.