I’ve just started on my assignment. I might obsessing over my code a little too much but I was wondering about other peoples view on this are. I’m working on my GUI at the moment and have read that it is good practice to instantiate instance variables where they are declared. In my work I find that I leave the instantiation of components to methods that build the GUI because it looks cleaner and because I find it easier to make sure I do all the set-up of the components required. I know that instantiation on declaration generally results in less NPE but does this not hinder the readability of the code?
Do the examiners take this level of detail into account?
My take is that declaration, instantiation and first use should be closely
grouped for singleton attributes. But I've found, especially for GUIs, that
grouping constructs of the same type enhances readability, code quality
and coding efficiency. For example, declaring a list of JButtons, instantiating
them in a list, and so on. Being able to cross check with nearly identical lines
above and below helps spot errors, and CTL-C/CTL-V works better if you can
avoid taking long jouorneys up and down the source code. That said, I then
switch over to set JButton state, button by button. This is kind of a ramble,
but I guess for me, there are tradeoffs to consider.
... Jim ... (P.S. What is NPE?)
BEE MBA PMP SCJP-6
Joined: May 26, 2008
Ok, thanks for your take on it. Your view certainly makes me think a little bit more about how I structure my code (something easily over looked when you are under pressure at work). NPE is NullPointerException BTW
I declared a lot of data members in my gui classes, but initialized them just when I needed them. And like Jim indicates you get easy copy/paste code and can spot mistakes a bit quicker. For example:
In my opinion it is more important for readibility to be consistent in the way you code, so your complete code base has the same "look and feel" and not different in each class.
Joined: May 26, 2008
Thanks Roel, that’s how I would normally do it. It’s good to have some confirmation that this is an acceptable method of practice. Looking at the project for the in the early stages leads me to believe that I’ll be asking a lot more questions. I’ve been surprised at the vagueness of the requirements and questioning myself on every decision made (makes for an interesting project though).