Wednesday, September 25, 2019

Don't pass references to your private objects

In the example above, the private variable author is a string. However, if author was an object, then the getAuthor method would return it by reference to the outside world (remember that primitive variables are passed by value and objects are passed by reference). 
Directly returning a private object reference from a privileged method essentially cancels privacy. Anyone can now make changes to the author object. Let's look at an example.
  1. function Book(author, price) {
  2. var details = {
  3. "author": author,
  4. "price": price
  5. };
  6. this.getDetails = function () { // anti pattern
  7. return details; // returns reference to details
  8. };
  9. }
  10. var book = new Book("James Joyce", "29.50");
  11. var bookDetails = book.getDetails();
  12. bookDetails.author = "Jane Austen"; // modifies private data
  13. bookDetails.price = "99.95";
  14. alert(book.getDetails().author); // => Jane Austen
  15. alert(book.getDetails().price); // => 99.95
Run
Although the details variable is private, the method getDetails() passes it by reference to the code outside the object. Therefore it is exposed to modification by clients of the Book which is shown in the last four statements in which both the author and price are updated.
One possible solution would be to clone the details object in the getAuthor() method and then return the clone. Alternatively you could return a new object that contains only those properties of the details object that the outside code is interested in and return it.

No comments:

Post a Comment