aspose file tools*
The moose likes Beginning Java and the fly likes Code design question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Code design question" Watch "Code design question" New topic
Author

Code design question

Rahul Ba
Ranch Hand

Joined: Oct 01, 2008
Posts: 205

I have seen many examples and read some where to



Now, my question is why we not created myList object at a first time i.e

Instead of doing

List myList = new ArrayList() we did

List myList; and then in the method we wrote

myList = new ArrayList();


why is it so? What difference it makes hence doing so?

Thanks for you time and co-opeartion.

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38363
    
  23
By using the name of the interface List, you give more flexibility. You can change the ArrayList implementation to another implementation (eg Vector, LinkedList) secure in the knowledge that it will make no difference to the correctness of your code.

This is called "program to the interface, not the implementation."

Other people will doubtless wish to give you more details.
Larry Frissell
Ranch Hand

Joined: May 16, 2008
Posts: 82
    
    2
Campbell's explanation of why we use List is correct, but I think you were asking a different question.

I read the question as why do we do this:



Instead of this:


or this:


If I am reading your question correctly, then I believe the answer is style.


Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38363
    
  23
If I've answered the wrong question, sorry. I would prefer to see such a field (not a local variable) instantiated in the constructor, both to prevent null problems, and to ensure it is always the same instance used.
Rahul Ba
Ranch Hand

Joined: Oct 01, 2008
Posts: 205
Hi Campbell,

Sorry, I did not get it. Can you explain more in detail.

I repat my question ... Why we do not write in this way...





but prefer to write

Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38363
    
  23
Creating a new ArrayList inside the doProcess() method is probably a bad idea; you will lose any information which has been added previously.
The first declaration

List myList = new ArrayList();

is better; it ensures that the List is always created when the class is instantiated, and reduces the risk of having it null. I would prefer (mainly for stylistic grounds; it probably has no performance effect) to see the field initialised in a constructorEven better, if you are sure you want the List to be the same List throughout the life of the object, would be to flag it "final" then you can be sure it won't become null, nor will you lose any information by mistake.
 
wood burning stoves
 
subject: Code design question