Created
July 3, 2012 14:18
Domain Models Expose Behavior, Not State
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html> | |
<head> | |
<title>Domain Models Expose Behavior, Not State</title> | |
<script type="text/javascript"> | |
// I model a Task that can be completed. | |
function Task( id, description, isComplete, dateCreated, dateCompleted ){ | |
// Store internal, private properties. | |
this._id = id; | |
this._description = description; | |
this._isComplete = isComplete; | |
this._dateCreated = dateCreated; | |
this._dateCompleted = dateCompleted; | |
} | |
// Define class propertiers. | |
Task.prototype = { | |
// I set the new description. | |
changeDescription: function( description ){ | |
this._description = description; | |
}, | |
// I complete the task. | |
complete: function(){ | |
// Make sure the task isn't already complete. | |
if (this.isComplete()){ | |
throw( new Error( "TaskAlreadyComplete" ) ); | |
} | |
// Flag as complete. | |
this._isComplete = true; | |
this._dateCompleted = new Date(); | |
}, | |
// I determine if the task is completed. | |
isComplete: function(){ | |
return( this._isComplete ); | |
}, | |
// I determine if the task is open. | |
isOpen: function(){ | |
return( !this.isComplete() ); | |
}, | |
// I re-open a completed task. | |
open: function(){ | |
// Make sure the task isn't already open. | |
if (this.isOpen()){ | |
throw( new Error( "TaskAlreadyOpen" ) ); | |
} | |
// Flag as open. | |
this._isComplete = false; | |
this._dateCompleted = null; | |
}, | |
// -- Acccessors for output and persistence. -- // | |
getDateCompleted: function(){ | |
// .. | |
}, | |
getDateCreated: function(){ | |
// .. | |
}, | |
getDescription: function(){ | |
// ... | |
}, | |
getID: function(){ | |
// ... | |
}, | |
getIsComplete: function(){ | |
// ... | |
} | |
}; | |
// -------------------------------------------------- // | |
// -------------------------------------------------- // | |
// Create our existing task. | |
var task = new Task( 1, "Buy flowers", false, "2012/07/02", null ); | |
// Mess with task. | |
console.log( "Task open?", task.isOpen() ); | |
task.complete(); | |
console.log( "Task open?", task.isOpen() ); | |
console.log( "Task complete?", task.isComplete() ); | |
// Try to close the task twice in a row. | |
try { | |
task.complete(); | |
} catch (error){ | |
console.log( "Error:", error.message ); | |
} | |
</script> | |
</head> | |
<body> | |
<!-- Left intentionally blank. --> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment