Java encapsulation & array -


does returning copy of contents of array instead of direct reference improve encapsulation of class? i'm wondering if considered best practice.

if understand correctly, trying encapsulate collection. if provide direct reference, there no encapsulation collection. user can want collection - set null. if providing deep copy of collection user, when modify copy, not modifying collection in class.

the best practice encapsulate whole collection never giving user reference collection. instead, interface via class methods. if need iterate on whole collection, best return iterator on collection, provide read-only access it.

say example have class bookcollection, has private list data member. if want consumers of code able add , remove books, etc., provide methods them so.

here example code:

public class bookcollection {     private list<book> books;      public bookcollection() {         this.books = new arraylist();     }      public void addbook(book book) {         this.books.add(book);     }      public void removebook(book book) {         this.books.remove(book);     }      public book get(int index) {         return this.books.get(index);     }      // etc.      public iterator<book> getiterator() {         return this.books.iterator();     } } 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -