<?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>preconditions Archives | Programming Zen</title>
	<atom:link href="https://programmingzen.com/tag/preconditions/feed/" rel="self" type="application/rss+xml" />
	<link>https://programmingzen.com/tag/preconditions/</link>
	<description>Meditations on programming, startups, and technology</description>
	<lastBuildDate>Fri, 29 Jul 2016 07:09:37 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
<site xmlns="com-wordpress:feed-additions:1">1397766</site>	<item>
		<title>In Praise of Function Pre and Postconditions</title>
		<link>https://programmingzen.com/in-praise-of-function-pre-and-postconditions/</link>
					<comments>https://programmingzen.com/in-praise-of-function-pre-and-postconditions/#comments</comments>
		
		<dc:creator><![CDATA[Antonio Cangiano]]></dc:creator>
		<pubDate>Sun, 03 Jul 2016 13:00:59 +0000</pubDate>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[clojure]]></category>
		<category><![CDATA[defensive programming]]></category>
		<category><![CDATA[design by contract]]></category>
		<category><![CDATA[elixir]]></category>
		<category><![CDATA[postconditions]]></category>
		<category><![CDATA[preconditions]]></category>
		<category><![CDATA[whiley]]></category>
		<guid isPermaLink="false">http://programmingzen.com/?p=1694</guid>

					<description><![CDATA[<p>I call it my billion-dollar mistake. It was the invention of the null reference. &#x2014; Sir Tony Hoare In mathematics, functions have a domain and a codomain. These are respectively the set of inputs and the set of possible outputs. The function then simply relates an input to an output. For example, consider the square root function: A function&#x2019;s definition is only complete when its domain and codomain are defined. For such a common function we generally implicitly assume that the domain and codomain are the set of nonnegative real numbers: You could, however, change the function by simply extending </p>
<p>The post <a href="https://programmingzen.com/in-praise-of-function-pre-and-postconditions/">In Praise of Function Pre and Postconditions</a> appeared first on <a href="https://programmingzen.com">Programming Zen</a>.</p>
]]></description>
										<content:encoded><![CDATA[<p style="text-align: right; font-style: italic; margin-bottom: 30px;">I call it my billion-dollar mistake. It was the invention of the null reference.<br />
— Sir Tony Hoare</p>
<p>In mathematics, functions have a domain and a codomain. These are respectively the set of inputs and the set of possible outputs. The function then simply relates an input to an output.</p>
<p>For example, consider the square root function:</p>
<div style="text-align: center;"><img decoding="async" src="https://s0.wp.com/latex.php?latex=f%28x%29+%3D+%5Csqrt%7Bx%7D&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" alt="f(x) = &#92;sqrt{x}" class="latex" /></div>
<p>A function’s definition is only complete when its domain and codomain<a id="fnref:1" class="footnote" title="see footnote" href="#fn:1">[1]</a> are defined.</p>
<p>For such a common function we generally implicitly assume that the domain and codomain are the set of nonnegative real numbers:</p>
<div style="text-align: center;"><img decoding="async" src="https://s0.wp.com/latex.php?latex=f%3A+%5Cmathbb%7BR%7D%5E%7B%2B%7D+%5Crightarrow+%5Cmathbb%7BR%7D%5E%7B%2B%7D&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" alt="f: &#92;mathbb{R}^{+} &#92;rightarrow &#92;mathbb{R}^{+}" class="latex" /></div>
<p>You could, however, change the function by simply extending the domain to all real numbers, which would require you to define the codomain as the set of complex numbers:</p>
<div style="text-align: center;"><img decoding="async" src="https://s0.wp.com/latex.php?latex=f%3A+%5Cmathbb%7BR%7D+%5Crightarrow+%5Cmathbb%7BC%7D&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" alt="f: &#92;mathbb{R} &#92;rightarrow &#92;mathbb{C}" class="latex" /></div>
<p>This function can then relate, say, <code>-1</code> to <code>i</code>.</p>
<p>When it comes to programming, things are not much different.<a id="fnref:2" class="footnote" title="see footnote" href="#fn:2">[2]</a> In most languages, we still call them functions, and they still relate an input to an output (after some computation).<a id="fnref:3" class="footnote" title="see footnote" href="#fn:3">[3]</a></p>
<p>Much like in mathematics, the input doesn’t necessarily have to be a number and can often be a composite data type, a list of arguments, or even other functions (in the case of higher-order functions, for example).</p>
<h3>Domain and Codomain Defined via Type Signature</h3>
<p>As far as most mainstream programming languages go, the parallels essentially stop there. In fact, most languages fail to provide us with built-in features to completely define the function by specifying its domain and codomain. And I would argue that we are missing out.</p>
<p>Statically typed programming languages partially offer a way to define the domain and codomain of a function, by specifying the parameters and return value types. Take the <code>Sqrt</code> method definition in C#:</p>
<pre class="prettyprint lang:c# mark:1 decode:true" title="Type-level domain and codomain constraints (in C#)">public static double Sqrt(double x)
{
  &#47;&#47;...
}</pre>
<p>An exception will occur if the argument passed to the function is not a double (or can’t be cast into a double). The same goes for the return value.</p>
<p>This type signature provides a basic element of safety. It ensures that we are actually passing a number to the function, instead of, say, <code>null</code> by mistake. It also ensures that we are returning a value in the first place and that the function’s return value is of the double type.</p>
<p>We essentially narrowed down<a id="fnref:4" class="footnote" title="see footnote" href="#fn:4">[4]</a> our domain and codomain to:</p>
<div style="text-align: center;"><img decoding="async" src="https://s0.wp.com/latex.php?latex=f%3A+%5Cmathbb%7BR%7D+%5Crightarrow+%5Cmathbb%7BR%7D&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" alt="f: &#92;mathbb{R} &#92;rightarrow &#92;mathbb{R}" class="latex" /></div>
<p>Amusingly, if we call <code>Math.Sqrt(-9)</code> in C#, the function will not raise an exception because both the argument and the return values fit the type declaration.</p>
<p>In fact, the function would return <code>Double.NaN</code>, which is the result of an undefined operation, but still technically a double. Other languages will handle the situation differently.<a id="fnref:5" class="footnote" title="see footnote" href="#fn:5">[5]</a></p>
<p>A significant number of software bugs are caused by programmer expectations being silently violated. Wouldn’t it be nice if we could use a feature to easily specify fine-tuned conditions on the acceptable input and output values like we do in mathematics?</p>
<p>For instance, ensuring that an error is automatically raised at runtime if the return value of the square root function isn&#8217;t a nonnegative number?</p>
<h3>Preconditions and Postconditions</h3>
<p>While developing the Eiffel programming language, Prof. Bertrand Meyer came up with the idea of <a href="https://en.wikipedia.org/wiki/Design_by_contract">Design by contract (DbC)</a>. Two key concepts of this software methodology are preconditions and postconditions, which are enforced integrity checks on specified input and output values, respectively.</p>
<p>Preconditions are slowly becoming more common. For example, Elixir has guard expressions, which allow us to limit the set of values the function will accept:</p>
<pre class="prettyprint lang:erlang mark:2,8 decode:true " title="Guards in Elixir">defmodule Math do
  def sqrt(x) when x &gt;= 0 do
    :math.sqrt(x)
  end
end

IO.puts Math.sqrt(9)    # Prints 3
IO.puts Math.sqrt(-9)   # Raises a FunctionClauseError</pre>
<p>Notice how an error is raised when we are trying to call the function with an input outside of the domain specified by the guard.</p>
<p>Guard expressions in named functions were introduced in Elixir in order to fully flesh out its powerful pattern matching capabilities.<a id="fnref:6" class="footnote" title="see footnote" href="#fn:6">[6]</a> Nevertheless, they act as preconditions that enable us to define the domain of the function.</p>
<p>To enforce checks on return values we need postconditions. For this example, I’ll use Clojure since it provides both preconditions and postconditions:</p>
<pre class="prettyprint lang:clojure mark:2,3,7,8 decode:true ">(defn limited-sqrt &#091;x&#093;
    {:pre  &#091;(pos? x)&#093;
     :post &#091;(&gt;= % 0), (&lt; % 10)&#093;}
    (Math&#47;sqrt x))

(limited-sqrt 9)   ;; 3.0
(limited-sqrt -9)  ;; AssertionError Assert failed: (pos? x)
(limited-sqrt 144) ;; AssertionError Assert failed: (&lt; % 10)
</pre>
<p>I intentionally made the example contrived by limiting the function codomain to values between 0 and 10, to demonstrate how postconditions are also caught at runtime (line 8).</p>
<h3>Extended Static Checking</h3>
<p>Some programming languages take the concept further by introducing <em>verifying compilers</em> that check the mathematical correctness and adherence to the formal specification.</p>
<p>The compiler will essentially take care of traversing all possible branches to determine whether the range of values the program could calculate meets the specification for the given function.</p>
<p>Creating such a compiler for an existing language is extremely hard. We are always contending with the <a href="https://en.wikipedia.org/wiki/Halting_problem" target="_blank">halting problem</a>. It is possible, however, to design languages specifically with that aim in mind.</p>
<p><a href="https://whiley.org/" target="_blank">Whiley</a> is one such language for the JVM.</p>
<p>Consider this example:</p>
<pre class="prettyprint lang:default mark:4,5 decode:true " title="Whiley example">import whiley.lang.System

function max(int x, int y) -&gt; (int z)
ensures x == z || y == z
ensures x &lt;= z &amp;&amp; y &lt;= z:
    if x &gt; y:
        return x
    else:
        return y

method main(System.Console console):
    console.out.println(max(4, 10))</pre>
<p>Whiley&#8217;s compiler will verify that x, y, and z meet the conditions indicated in the specification (on lines 4 and 5). Namely, that the returned value is either of the two arguments and that both of them are less than or equal to it.</p>
<p>If we create a faulty version of the algorithm as shown below, we’ll catch the error before even running the program:</p>
<pre class="prettyprint lang:default mark:6,8 decode:true ">import whiley.lang.System

&#47;&#47; Bad implementation
function max(int x, int y) -&gt; (int z)
ensures x == z || y == z
ensures x &lt;= z &amp;&amp; y &lt;= z:
    if x &gt; y:
        return y
    else:
        return x

method main(System.Console console):
    console.out.println(max(4, 10))</pre>
<p>In fact, although <code>max(4, 10)</code> does not enter the if branch, the compiler determines that there are inputs for which that return y would not satisfy the highlighted postcondition.</p>
<p>True enough if you consider <code>max(3, 2)</code> for a moment. x (3) &gt; y (2), so in this faulty implementation, we return z (2). However, x (3) is not less than or equal to z (2), so the postcondition fails.</p>
<p>Whiley is an extreme case of course, and as discussed, its verifying compiler is a virtually intractable problem for regular programming languages which were not specifically designed for it. Nevertheless, I wanted to show you how far this powerful concept can be pushed.</p>
<h3>Conclusion</h3>
<p>I would love to see pre and postconditions become built-in features of more mainstream programming languages.</p>
<p>Especially since many mainstream programming languages don’t offer referential transparency. Side effects caused by mutable data structures and having to account for state mean that we have even less predictability about return values than in purely functional programming languages.</p>
<p>As shown by Elixir, Clojure, and even Whiley, adding such specifications doesn&#8217;t require any significant syntactic overhead either.</p>
<p>With dynamically typed programming languages we stress the importance of having tests because we don’t have a compiler to catch as many of our mistakes. (Though testing is key either way.)</p>
<p>Pre and postconditions add a complementary layer of safety, regardless of the language&#8217;s typing system. By using both Design by Contract principles and testing, we can build more robust software. (Definitely check out other features of DbC as well, including class invariants. There are lots of good ideas in there.)</p>
<p>If you’d like to get started, you can probably find a library for your favorite language. If not, creating your own should be fairly easy.</p>
<p>However, I’d advocate for such conditions/assertions to be a core part of most languages. And that’s because of the difference in the adoption rate of opt-in vs opt-out features.</p>
<p>With pre and postconditions built into the language, documented in the intro tutorial that everyone reads, you’ll cultivate a community with a penchant for defensive programming, who will actually make use of the feature.</p>
<p>&nbsp;</p>
<div class="footnotes">
<hr />
<ol>
<li id="fn:1">Some readers might be more familiar with the word <em>range</em> or <em>image</em>. In our examples, range and codomain coincide, even though in general, the range is a subset of the codomain. <a class="reversefootnote" title="return to article" href="#fnref:1">^</a></li>
<li id="fn:2">When a function has an algorithmic bug and we get the wrong output, we are still defining a function. Just not the intended one. <a class="reversefootnote" title="return to article" href="#fnref:2">^</a></li>
<li id="fn:3">I’ll use the word function even when the proper nomenclature of the specific language might call for another word, such as <em>method</em>. <a class="reversefootnote" title="return to article" href="#fnref:3">^</a></li>
<li id="fn:4">Obviously, doubles are represented in memory as double precision floating-point numbers, and therefore not actual real numbers. So they are technically a subset of the rational numbers <img decoding="async" src="https://s0.wp.com/latex.php?latex=%5Cmathbb%7BQ%7D&#038;bg=ffffff&#038;fg=000&#038;s=0&#038;c=20201002" alt="&#92;mathbb{Q}" class="latex" />. <a class="reversefootnote" title="return to article" href="#fnref:4">^</a></li>
<li id="fn:5">Both Ruby and Julia, for example, will raise a <code>DomainError</code> in such a scenario. <a class="reversefootnote" title="return to article" href="#fnref:5">^</a></li>
<li id="fn:6">Here we could have a second declaration with <code>when x &lt; 0</code> to match function calls with negative arguments, perhaps leveraging that function implementation to provide a more informative error message. <a class="reversefootnote" title="return to article" href="#fnref:6">^</a></li>
</ol>
</div>
<p>The post <a href="https://programmingzen.com/in-praise-of-function-pre-and-postconditions/">In Praise of Function Pre and Postconditions</a> appeared first on <a href="https://programmingzen.com">Programming Zen</a>.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://programmingzen.com/in-praise-of-function-pre-and-postconditions/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
		<post-id xmlns="com-wordpress:feed-additions:1">1694</post-id>	</item>
	</channel>
</rss>
