i got my SCJP in 2001 and wrote code for several years but now after about 6 years of not writing i am kind of like a greenhorn again. anyway i threw together this program using copy/paste/edit from other programs i have written(and a little help from here at the ranch) and it is raising questions and doubts about how i am doing things.
1 the methods: i think i will get rid of initComponents() since the constructor doesn't do much anyway. i think i will keep center() since i have to use it more than once. about main(), i always did it that way, but can't i set the size,center,and all that in the constructor?
2 the imports: i think i am importing too much. using * is good if there are a lot of things to import from that package but this is a very simple program.
3 the variables: this is my main question. like i said i threw this together in a hurry, so it is a hodgepodge of member and local variables. sometimes we have no choice:we need the variable in more than one method, we can't instantiate when we declare, or we need a new instance each time a method is called. i think it is best to instantiate when we declare if we can. member vs local, each has advantages. if we need a new instance each time and the method gets called a lot then i think it is better to use a local variable. but sometimes we can do it either way. so anyway what would you change if this was your program?
That decision allows it to have more than one ActionListener, which could happen as soon as you put two JButtons into your GUI. The ActionListener should be a nested class; I'm in the habit of making it an anonymous inner class but the other day when I found I had anonymous inner classes nested two deep I decided that was falling off the "best practices" cart and redesigned it to use named inner classes.
good advice for the future, but as you can see this is a very simple program with only one action. my main question is about member vs local variables. maybe that would have been a better topic, but i want any feedback.
Randall Twede wrote:my main question is about member vs local variables.
Ah yes. You have some of your GUI setup done as part of declaring those member variables, and some of it done in the initComponents method. You should put it all in one place -- that would be in the initComponents method, since it can't all be done as a side effect of declaring variables. So just declare the member variables, don't initialize them at the same time. Put the initializations into the initComponents method along with the other initialization code.