<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Rantings in the dark &#187; jsContract</title>
	<atom:link href="http://kinsey.no/blog/index.php/category/projects/jscontract/feed/" rel="self" type="application/rss+xml" />
	<link>http://kinsey.no/blog</link>
	<description>Because I want to be like the cool kids too</description>
	<lastBuildDate>Mon, 03 Oct 2011 22:01:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>jsContract &#8211; Code contracts for Javascript</title>
		<link>http://kinsey.no/blog/index.php/2010/02/03/jscontract-code-contracts-for-javascript/</link>
		<comments>http://kinsey.no/blog/index.php/2010/02/03/jscontract-code-contracts-for-javascript/#comments</comments>
		<pubDate>Wed, 03 Feb 2010 21:01:10 +0000</pubDate>
		<dc:creator>oyvind.kinsey</dc:creator>
				<category><![CDATA[jsContract]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[code contracts]]></category>
		<category><![CDATA[design by contract]]></category>
		<category><![CDATA[instrumentation]]></category>
		<category><![CDATA[Javascript]]></category>

		<guid isPermaLink="false">http://kinsey.no/blog/?p=214</guid>
		<description><![CDATA[I have recently started using code contracts in one of my .net projects and I came to think that since most of the code I produce these days are in Javascript, why don&#8217;t I try it there to! Well, easier said than done &#8211; there just is no decent frameworks for this. During my searching [...]]]></description>
			<content:encoded><![CDATA[<p>I have recently started using <a href="http://en.wikipedia.org/wiki/Design_by_contract" target="_blank">code contract</a>s in one of my .net projects and I came to think that since most of the code I produce these days are in Javascript, why don&#8217;t I try it there to!</p>
<p>Well, easier said than done &#8211; there just is no decent frameworks for this.</p>
<p>During my searching I found some references to libraries such as <a href="http://www.cerny-online.com/cerny.js/documentation/guides/contracts" target="_blank">Cerny.js</a> and <a href="http://weblogs.mozillazine.org/weirdal/archives/016921.html" target="_blank">ecmaDebug</a>, but these just didn&#8217;t make the cut  - they all required heavy (and hard to follow) restructuring of your code to make them work.</p>
<p>So what did I do? Well I made <a href="http://kinsey.no/projects/jsContract/" target="_blank">jsContract</a>, a library that is clean and .. wait for it .. extremely easy to use!<span id="more-214"></span></p>
<p style="padding-left: 30px;"><strong>If you want a quick view on what Code Contracts can give you, take a look at </strong><a href="http://kinsey.no/projects/jsContract/test2.html" target="_blank"><strong>this example</strong></a><strong>!</strong></p>
<p>The following method comes from the sample code in the link above</p>
<pre class="brush: jscript; title: ; notranslate">    function _internalMethod(a, b){
        Contract.expectNumber(a);
        Contract.expectNumber(b);
        Contract.expectWhen(config.mode === &quot;divide&quot;, b &gt; 0, &quot;Divisor cannot be 0&quot;);
        Contract.expectWhen(config.mode === &quot;multiply&quot;, a &gt; 0 &amp;&amp; b &gt; 0, &quot;The multiplicands cannot be 0&quot;);
        Contract.guaranteesNumber();
        Contract.guarantees(function(result){
            return result &gt; 0;
        }, &quot;Result must be &gt; 0&quot;);

        if (config.mode == &quot;divide&quot;) {
            return a / b;
        }
        // At this point config.mode must be &quot;multiply&quot;
        return a * b;
    }
</pre>
<p>As you can see, the contract statements does not ruin the flow of the code, rather, it helps to document it.<br />
By looking at the contract at the start of the method, you can instantly see what the method expects and what it will return.<br />
This also helps you reduce code since you do not need to check for conditions that are not allowed according to the contract.</p>
<h2>Postconditions</h2>
<p>So, you might be wondering about how the <code>Contract.guarantees</code> methods work? How can a statement placed in the head of the method possibly check the return value of the method?<br />
Well, the above code will actually not check the return value when run, but by running it through  <code>Contract.instrument</code> we can get code that will!<br />
This is the output created by <code>Contract.instrument </code>for the above code</p>
<pre class="brush: jscript; title: ; notranslate">
    function _internalMethod(a, b){
        arguments.callee.isInstrumented = true;
        /*preconditions*/
        Contract.expectNumber(a);
        Contract.expectNumber(b);
        Contract.expectWhen(config.mode === &quot;divide&quot;, b &gt; 0, &quot;Divisor cannot be 0&quot;);
        Contract.expectWhen(config.mode === &quot;multiply&quot;, a &gt; 0 &amp;&amp; b &gt; 0, &quot;The multiplicands cannot be 0&quot;);
        var __return = (function(a, b){
            if (config.mode == &quot;divide&quot;) {
                return a / b;
            }
            // At this point config.mode must be &quot;multiply&quot;
            return a * b;
        }(a, b));
        /*postconditions*/
        Contract.guaranteesNumber(__return);
        Contract.guarantees(__return, function(result){
            return result &gt; 0;
        }, &quot;Result must be &gt; 0&quot;);
        return __return;
    }
</pre>
<p>As you can see the code block has been wrapped in an anonymous function, the postconditions has been moved below this and has been rewritten so that they take the result as an argument.</p>
<p><strong>We now have both pre- and postconditions checking our code!</strong></p>
<p>The framework handles nested functions just as you would expect it to and the only real change to your code is the extra anonymous function that is inserted when the parser finds a postcondition in use.</p>
<p>But now you might be wondering, how do we get the instrumented code in to our applications?</p>
<p>For this you have several options</p>
<ul>
<li>Use tools like <a href="http://kinsey.no/projects/jsContract/" target="_blank">this</a> to convert the code for you before pasting it into a js file</li>
<li>Use it as a part of you build process for automated generation
<ul>
<li>a commandline tool will be available shortly</li>
</ul>
</li>
<li>Use dynamic loading and instrumentation at runtime</li>
</ul>
<p>The last option is only viable for development scenarios, but that is mainly when code contracts are needed anyways.<br />
To load scripts dynamically you can either use your own AJAX code, or use the built in Contract.load method</p>
<p>The following code is taken from the  <a href="http://kinsey.no/projects/jsContract/test.html" target="_blank">example </a>available with the framework</p>
<pre class="brush: jscript; title: ; notranslate">
var instrument = (location.search &amp;&amp; location.search.indexOf(&quot;instrument=true&quot;) !== -1);
Contract.load(&quot;MyClass.js&quot;, instrument, function(){
    try {
        var myClass = new MyClass({
            mode: &quot;multiply&quot;
        });

        var result = myClass.publicMethod(34, 5, 3);
    }
    catch (ex) {
        alert(ex.message);
    }
});
</pre>
<p>This code loads regular or instrumented code depending on the query string.</p>
<p>Doesn&#8217;t it look cool?</p>
<p>Its available at <a href="http://github.com/oyvindkinsey/jsContract" target="_blank">github</a> and will most likely be licensed with an MIT style license.</p>
<p>Anybody want to join in, maybe help with some documentation etc?</p>
<p>Drop me a note if so!</p>
<p><strong>Note:</strong> This is the first draft, I started this project today.</p>
<p>The parser is quite naive and strings matching &#8216;function(&#8216; etc and unmatched { and } in comments  will break it. But this is a work in progress <img src='http://kinsey.no/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>Update 1 04.02:</strong> { and } in comments are now safely handled, and several small issues has been corrected.</p>
<p>Now I only need to validate that the functions the parser finds are not part of a comment.</p>
<p><strong>Update 2 04.02:</strong> The parser has now been fixed, it now completely ignores anything in the comments. As far as I know this means that as long as the code validates the parser should be solid as a rock!</p>
]]></content:encoded>
			<wfw:commentRss>http://kinsey.no/blog/index.php/2010/02/03/jscontract-code-contracts-for-javascript/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
	</channel>
</rss>

