• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Code design question

 
Rahul Ba
Ranch Hand
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Pie
Posts: 49841
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 82
2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49841
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 206
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49841
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic