What is the best practice in wrting the same code
Hi,
This i posted in stackoverflow.com, i received some suggestions, i also like to get more suggestions from your site.
Is it a good practice to use properties as local variable. In cases where there are many methods which uses some variables, In each method the variable value changes. This avoids many times creating new variables and the code increases. Any suggestion?
private void method1(){
int totalLength = length1 + 10;
int totalBreath = (breath1 + breath2) + 20;
int size = (totalLength * totalLength);
System.out.println(size);
}
private void method2(){
int totalLength = length1 + 20;
int totalBreath = (breath1 + breath2) + 30;
int size = (totalLength * totalLength);
System.out.println(size);
}
private void method3(){
int totalLength = length1 + 60;
int totalBreath = (breath1 + breath2) + 10;
int size = (totalLength * totalLength);
System.out.println(size);
}
As you can see, totalLength, totalBreath, size is repeated in every method. Can i make them as fields of the class? So, i need not declare it in every method.
private void method1(){
totalLength = length1 + 10;
totalBreath = (breath1 + breath2) + 20;
size = (totalLength * totalLength);
System.out.println(size);
}
Re: What is the best practice in wrting the same code
Hello! Please use [code][/code] tags when posting code so we can read with ease :D
To your question,
It is good practice to only make a variable a class/instance variable if that variable itself is going to be used in multiple places. In your case, you're not really using the variables anywhere other than locally (the values only have meaning in the context of the method they are currently being used in). So, you should keep them local.
If you think of variables as 'attributes' as they are sometimes referred, then making them class-scope makes no sense at all.
A general rule is if the variable only has meaning in a local context, keep it local. You don't really gain anything other than confusion by putting it in the class.
Re: What is the best practice in wrting the same code
Quote:
Originally Posted by
quad64bit
Hello! Please use [code][/code] tags when posting code so we can read with ease :D
To your question,
It is good practice to only make a variable a class/instance variable if that variable itself is going to be used in multiple places. In your case, you're not really using the variables anywhere other than locally (the values only have meaning in the context of the method they are currently being used in). So, you should keep them local.
If you think of variables as 'attributes' as they are sometimes referred, then making them class-scope makes no sense at all.
A general rule is if the variable only has meaning in a local context, keep it local. You don't really gain anything other than confusion by putting it in the class.
Nice and crisp answer. Thanks