Created
October 4, 2009 11:05
-
-
Save jauco/201307 to your computer and use it in GitHub Desktop.
Design by contract in javascript
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
//Design by contract function | |
function $contracted(pre, post, func){ | |
return function(){ | |
var paramsAsArray, | |
funcName, | |
retVal; | |
paramsAsArray = Array.slice(arguments) | |
funcName = func.toString().substr('function '.length); | |
funcName = funcName.substr(0, funcName.indexOf('('));//strip of everything, but the name | |
if (!pre.apply(this, paramsAsArray)){ | |
console.error("pre condition failed for '",func,"' with: ",paramsAsArray); | |
throw "pre condition failed for '"+ funcName+"'"; | |
} else { | |
retVal = func.apply(this, paramsAsArray); | |
if (!post(retVal)){ | |
console.error("post condition failed for '",func,"'. It returned '",retVal,"' with: ",paramsAsArray); | |
throw "post condition failed for '"+ funcName+"'"; | |
} | |
return retVal; | |
} | |
} | |
} | |
//Example: | |
var doSomething = $contracted( | |
function pre(a,b,c) b > 0, //javascript 1.8 needed for the fancy lambda syntax. else write: function pre(a,b,c){return b>0 } | |
function post(r) r > 0, | |
function doSomething(a,b,c){ | |
return a + (c / b); | |
} | |
); | |
doSomething(1,2,3); | |
doSomething(0,0,0); | |
doSomething(0,3,0); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment