Skip to content

Instantly share code, notes, and snippets.

@dearshrewdwit
Created March 8, 2021 12:13
Show Gist options
  • Save dearshrewdwit/7a35bb1c134c227cf0a9c9b5da23b27a to your computer and use it in GitHub Desktop.
Save dearshrewdwit/7a35bb1c134c227cf0a9c9b5da23b27a to your computer and use it in GitHub Desktop.
Demo of secret diary encapsulation example
// using classes together
// lower cohesion
class SecretDiary {
constructor() {
this.entries = []
this.isLocked = true
}
lock() {
this.isLocked = true
}
unlock() {
this.isLocked = false
}
addEntry(str) {
if (this.isLocked) { throw new Error }
this.entries.push(str)
}
getEntries() {
if (this.isLocked) { throw new Error }
return this.entries
}
}
// Higher cohesion - Example 1
class Diary {
constructor() {
this.entries = []
}
addEntry(str) {
this.entries.push(str)
}
getEntries() {
return this.entries
}
}
class SecretDiary {
constructor() {
this.diary = new Diary()
this.isLocked = true
}
lock() {
this.isLocked = true
}
unlock() {
this.isLocked = false
}
addEntry(str) {
if (this.isLocked) { throw new Error }
this.diary.addEntry(str)
}
getEntries() {
if (this.isLocked) { throw new Error }
return this.diary.getEntries()
}
}
// Higher cohesion - Example 2
class Lock {
constructor() {
this.isLocked = false
}
lock() {
this.isLocked = true
}
unlock() {
this.isLocked = false
}
}
class SecretDiary {
constructor() {
this.entries = []
this.lock = new Lock()
}
lock() {
this.lock.lock()
}
unlock() {
this.lock.unlock()
}
addEntry(str) {
if (this.lock.isLocked) { throw new Error }
this.entries.push(str)
}
getEntries() {
if (this.lock.isLocked) { throw new Error }
return this.entries
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment