HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Using temporary variables or calling a method directly

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
methodtemporaryusingvariablesdirectlycalling

Problem

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

            }
        });

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 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

Context

StackExchange Code Review Q#60223, answer score: 5

Revisions (0)

No revisions yet.