patternjavaMinor
Using temporary variables or calling a method directly
Viewed 0 times
methodtemporaryusingvariablesdirectlycalling
Problem
Which of these approaches for a button click is better/faster/more efficient, and why?
Approach One:
Approach Two:
Approach One:
Button button = (Button) findViewById(R.id.button_english_splash);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(v.getContext(), "Clicked!", Toast.LENGTH_SHORT)
.show();
}
});Approach Two:
((Button) findViewById(R.id.button_english_splash))
.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(v.getContext(), "Clicked!",
Toast.LENGTH_SHORT).show();
}
});Solution
Regarding speed and memory, both are completely equivalent.
The only thing this boils down to is readability. In which case the first option has an advantage.
By storing the
Also, method calls like
I would recommend sticking to the first option. Perhaps not always, but mostly.
Other comments:
The only thing this boils down to is readability. In which case the first option has an advantage.
By storing the
Button button = (Button) findViewById(R.id.button_english_splash); in a temporary variable, you have the opportunity to give it a good variable name, in case the R.id identifier is not good enough.Also, method calls like
((Button) findViewById(R.id.button_english_splash)).someMethod are often not very readable as there are several parenthesis that are added.I would recommend sticking to the first option. Perhaps not always, but mostly.
Other comments:
- Remove
// TODO Auto-generated method stubcomments from your code
- It is good that the
onClickmethod has been marked with@Override.
- Declare the onClick method inside the XML instead
Context
StackExchange Code Review Q#60223, answer score: 5
Revisions (0)
No revisions yet.