What is the right way or the best approach ?
1- Writing the Instance variable directly inside the methods
or
2- Passing variables from where to call
int number1;
int number2;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
number1 = 10;
number2 = 20;
// call first approach
sum();
// call second approach
sum(number1,number2);
}
// First approach
private int sum(){
return number1 number2;
}
// Second approach
private int sum(int number1,int number2){
return number1 number2;
}
}
CodePudding user response:
There is no correct or wrong in this it totally depends on your use case if you are using number1 number2 only in sum() method then you should go for the second approach but if you are changing values of number1 and number2 and you want that changed values in another method then you should go for the first approach.
CodePudding user response:
There is no absolute correct way, it depends on your use case. Having said that, second way is much more cleaner and reusable.
First approach - sum method is very specific and local. It can only do one thing, sum number1
and number2
variables.
Second approach - sum method is very generic and had absolute 0 side affects. We can also move it to a util file and reuse it throughout a module or project.
CodePudding user response:
I would highly recommend the call second approach
, since not only making it look cleaner but also no external dependent values is being used thus only depend on the variables passed on the function sum
.
sum(number1,number2);
So eventually when the operation inside the sum has become complex that you need to move them on another class like Utilities, it would make more sense to use 2nd approach for reusability and flexibility of the code.