Is there any difference between passing variables into method or declaring them at the top of the class?
Method 1
private double price; private void calculateStockWorth(){ price = regularMarketPrice.getRegularMarketPrice(); calculateStockRating(); } private void calculateStockRating(){ if(price < 200){ //do something } else { //do something else } }
And Method 2
private void calculateStockWorth(){ double price = regularMarketPrice.getRegularMarketPrice(); calculateStockRating(price); } private void calculateStockRating(double stockPrice){ if(stockPrice < 200){ //do something } else { //do something else } }
Sorry if this is a weird or stupid question, I’m still sort of a beginner, but I just never heard someone talk about the difference between these 2.
Advertisement
Answer
In the first case the variable can be used by other functions within the same file (as it is private), the value can also be modified in between(i.e, in other function or in the second function) if required.
However, for the second method, it will just pass the value and perform the required functions. The scope of price is also local in second case, so it is not accessible.