Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

Which of these approaches for a button click is better/faster/more efficient, and why?

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();

            }
        });
share|improve this question
1  
the second approach is useful only if you need to write a fast code to test something. In a real application the first approach is much better –  Marco Acierno Aug 16 at 10:40
    
If you have two horses, the best way to find out which is faster is to race them. As for the questions of "better" and "more efficient", we need more criteria for which to judge these on. –  nhgrif Aug 16 at 17:05

1 Answer 1

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 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 stub comments from your code
  • It is good that the onClick method has been marked with @Override.
  • Declare the onClick method inside the XML instead
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.