-1

I can't seem to find a direct answer, and it seems I've seen it done mulitple ways, here and else where. Is there even a better way to define that I have not seen? Which is the more proper way to define:

    Button image1;
Button image2;
Button image3;
Button image4;
Button image5;
Button image6;
Button image7;

Or

  Button  image1,image2,image3,image4,image5,image6,
  image7;
Oliver
  • 65
  • 10
  • I prefer each variable to be declared separately. This results in more readable code and the purpose of each variable can be separately documented. Also, possible duplicate of http://stackoverflow.com/questions/100633/why-do-you-not-declare-several-variables-of-the-same-type-on-the-same-line – Pravin Sonawane Nov 25 '16 at 18:19

2 Answers2

4

Given that your button variable names end in numbers that are monotonically increasing, it suggests that you're creating a collection of like buttons with similar function, and if so, it seems like "none of the above" may be the best answer. Consider creating a collection of buttons:

private List<Button> imageButtons = new ArrayList<>();

And then creating and adding the buttons you need.

  • Thanks for my first up-vote!! – DontKnowMuchBut Getting Better Nov 25 '16 at 18:01
  • I like this method, though I do have other buttons with other names in the activity as well. These are part of a gallery with an image set as the background of a button, once clicked it opens an expanded image view of the image and gives the user other options. The buttons are basically thumbnails of nature photographs. Would work with unique button names? Such as Button Cat; Button dog; ect... ect? – Oliver Nov 25 '16 at 18:07
  • @Oliver: you can use a `HashMap` if you want a collection that ties a name String to a button, or you could create a wrapper class to hold the Button, its name, etc. Also Luke's answer looks good... 1+ to it. – DontKnowMuchBut Getting Better Nov 25 '16 at 18:15
1

There is no "proper way". The way you define your variables depends on a few factors - the main being javadoc. In your first example, you can give each variable its own javadoc, while in the second, all the buttons would share a javadoc comment. For example:

/**
 * I am button a.
 */
Button a;

/**
 * I am button b.
 */
Button b;

/**
 * I am button c.
 */
Button c;

Each button above has its own javadoc comment.

/**
 * These are some buttons.
 */
Button a, b, c;

While in this example all of the variables above share a javadoc comment, so which method you use depends on what you want to do.

Although in the specific example you gave, @DontKnowMuchButGettingBetter is correct, an array would work best for storing your buttons.

For an unknown amount of buttons:

List<Button> buttons = new ArrayList<>();

For a known amount of buttons:

  • Button[] buttons = new Button[]{new Button("A"), new Button("B")};

or

  • Button[] buttons = new Button[numberOfButtons];
Community
  • 1
  • 1
Luke Melaia
  • 1,470
  • 14
  • 22