03.09.2015 Views

Design Patterns

Download - Assembla

Download - Assembla

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

CHAPTER 3 ■ ENCAPSULATION AND INFORMATION HIDING 31<br />

},<br />

getIsbn: function() {<br />

return this._isbn;<br />

},<br />

setIsbn: function(isbn) {<br />

if(!this.checkIsbn(isbn)) throw new Error('Book: Invalid ISBN.');<br />

this._isbn = isbn;<br />

},<br />

getTitle: function() {<br />

return this._title;<br />

},<br />

setTitle: function(title) {<br />

this._title = title || 'No title specified';<br />

},<br />

getAuthor: function() {<br />

return this._author;<br />

},<br />

setAuthor: function(author) {<br />

this._author = author || 'No author specified';<br />

},<br />

display: function() {<br />

...<br />

}<br />

};<br />

In this example, all of the attributes have been renamed. An underscore is added to the<br />

beginning of each, signifying that it is intended to be private. This is still a valid variable name<br />

in JavaScript, since the underscore is a legal first character in an identifier.<br />

This naming convention can be applied to methods as well. Let’s say that a programmer<br />

using your class is having a hard time creating an instance because he keeps getting “Invalid<br />

ISBN” errors. He could use the public method checkIsbn to run through each possible character<br />

for the checksum digit (there are only ten) until he finds one that passes, and use that to<br />

create an instance of Book. You should prevent that sort of behavior because it is likely that the<br />

ISBN created will still be invalid. To do this, you can change the method declaration from this<br />

checkIsbn: function(isbn) {<br />

...<br />

},<br />

to this<br />

_checkIsbn: function(isbn) {<br />

...<br />

},

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!