<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" version="2.0" xml:base="http://qedcode.com">
<channel>
 <title>Q.E.D. Code</title>
 <link>http://qedcode.com</link>
 <description>Q.E.D. is about confidence in software. It is a system of coding practices by which we can write mathematically provable software in any language.</description>
 <language>en</language>
<feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/rss+xml" href="http://feeds.feedburner.com/qedcode" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="qedcode" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><item>
 <title>Predassert</title>
 <link>http://qedcode.com/content/predassert</link>
 <description>&lt;p&gt;I was inspired by Robert C. Martin’s &lt;a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882"&gt;Clean Code&lt;/a&gt; to fix a problem with Microsoft’s unit testing framework. &lt;a href="http://msdn.microsoft.com/en-us/library/ms243413%28VS.80%29.aspx"&gt;Assert.AreEqual(object expected, object actual)&lt;/a&gt;. How do you remember which is the expected value and which is the actual?&lt;/p&gt;
&lt;p&gt;In JUnit and it’s younger .NET cousin NUnit, the method name makes it a bit more clear. &lt;a href="http://kentbeck.github.com/junit/javadoc/latest/org/junit/Assert.html#assertEquals(java.lang.Object,%20java.lang.Object)"&gt;Assert.assertEquals(Object expected, Object actual)&lt;/a&gt;. The code reads more like a sentence (albeit one spoken by Yoda).&lt;/p&gt;
&lt;pre&gt;assertEquals(&lt;span style="color: maroon"&gt;3&lt;/span&gt;, theResult);&lt;/pre&gt;&lt;p&gt;I was further inspired by BDD systems like &lt;a href="http://nspec.tigris.org/"&gt;NSpec&lt;/a&gt;, which makes the code more grammatically correct.&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: #2b91af"&gt;Specify&lt;/span&gt;.That( theResult ).ShouldEqual( &lt;span style="color: maroon"&gt;3&lt;/span&gt; );&lt;/pre&gt;&lt;p&gt;Readability of the code is only one of the concerns. The other is readability of the unit test failures. Assert.AreEqual() writes out a good failure message, because it can give you both the expected and the actual value. But more complex assertions do not provide useful failure messages. To solve these issues within the Microsoft unit testing space, I created Predassert.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Yet another library with a class named “Is”&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The primary goal of Predassert is that one line of code expresses both a predicate and an assertion. A predicate is executable and can determine if something is true or false. An assertion is human readable and explains why a test fails.&lt;/p&gt;
&lt;p&gt;Predassert accomplishes this goal through a fluent interface.&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: #2b91af"&gt;Pred&lt;/span&gt;.Assert( theResult, &lt;span style="color: #2b91af"&gt;Is&lt;/span&gt;.EqualTo(&lt;span style="color: maroon"&gt;3&lt;/span&gt;) );&lt;/pre&gt;&lt;p&gt;The “Is” class declares several static methods that generate assertion predicates. For example:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: #2b91af"&gt;Pred&lt;/span&gt;.Assert( &lt;span style="color: blue"&gt;new&lt;/span&gt; &lt;span style="color: #2b91af"&gt;List&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;(), &lt;span style="color: #2b91af"&gt;Is&lt;/span&gt;.Empty&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;() );
&lt;span style="color: #2b91af"&gt;Pred&lt;/span&gt;.Assert( referenceA, &lt;span style="color: #2b91af"&gt;Is&lt;/span&gt;.SameAs(referenceB) );
&lt;span style="color: #2b91af"&gt;Pred&lt;/span&gt;.Assert( bob, &lt;span style="color: #2b91af"&gt;Is&lt;/span&gt;.NotNull&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;() );&lt;/pre&gt;&lt;p&gt;You also have “Has” for properties and “Contains” for collections.&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: #2b91af"&gt;Pred&lt;/span&gt;.Assert( bob, &lt;span style="color: #2b91af"&gt;Has&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;.Property(person =&amp;gt; person.Name, &lt;span style="color: #2b91af"&gt;Is&lt;/span&gt;.EqualTo(&lt;span style="color: maroon"&gt;&amp;quot;Bob&amp;quot;&lt;/span&gt;) );
&lt;span style="color: #2b91af"&gt;Pred&lt;/span&gt;.Assert( queue, &lt;span style="color: #2b91af"&gt;Contains&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;GameRequest&lt;/span&gt;&amp;gt;.That(&lt;span style="color: #2b91af"&gt;Has&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;GameRequest&lt;/span&gt;&amp;gt;.Property(
    request =&amp;gt; request.Person, &lt;span style="color: #2b91af"&gt;Is&lt;/span&gt;.SameAs(bob))));&lt;/pre&gt;&lt;p&gt;You can even combine predicates with “And”.&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: #2b91af"&gt;Pred&lt;/span&gt;.Assert(bob,
    &lt;span style="color: #2b91af"&gt;Has&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;.Property(person =&amp;gt; person.FirstName, &lt;span style="color: #2b91af"&gt;Is&lt;/span&gt;.EqualTo(&lt;span style="color: maroon"&gt;&amp;quot;Bob&amp;quot;&lt;/span&gt;)
    .And(&lt;span style="color: #2b91af"&gt;Has&lt;/span&gt;&amp;lt;&lt;span style="color: #2b91af"&gt;Person&lt;/span&gt;&amp;gt;.Property(person =&amp;gt; person.LastName, &lt;span style="color: #2b91af"&gt;Is&lt;/span&gt;.EqualTo(&lt;span style="color: maroon"&gt;&amp;quot;Perry&amp;quot;&lt;/span&gt;))
);&lt;/pre&gt;&lt;p&gt;As you can see, you can get pretty carried away.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Uniformity of expression&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;The fluent interface is not the goal. Uniformity of expression is the goal. The fluent interface is just a means to that end. When you use Microsoft’s unit testing framework, &lt;a href="http://msdn.microsoft.com/en-us/library/ms243754%28VS.80%29.aspx"&gt;Assert.IsTrue(bool condition, string message)&lt;/a&gt; makes you express the assertion in both code and text. But when you use Predassert, the fluent interface generates both from the same syntax.&lt;/p&gt;
&lt;p&gt;The “Has” class will insert the property name into the assertion message. There is no need to retype it, no chance of copy/paste errors, and no extra work if you use the “Rename” refactoring tool.&lt;/p&gt;
&lt;p&gt;The “Contains” class will enumerate the collection and explain why each element failed the test. This extra detail usually gives you enough information to diagnose an error directly from the failure message, rather than by setting breakpoints.&lt;/p&gt;
&lt;p&gt;Predassert is currently distributed as part of the &lt;a href="http://correspondence.codeplex.com/"&gt;Correspondence&lt;/a&gt; library on CodePlex. I’m allowing it to grow organically as I need features. When it is more mature, perhaps I will separate it. Until then, you can download the Correspondence source code and extract the Predassert project for your own use.&lt;/p&gt;
</description>
 <comments>http://qedcode.com/content/predassert#comments</comments>
 <pubDate>Mon, 04 Jan 2010 22:34:00 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">19 at http://qedcode.com</guid>
</item>
<item>
 <title>Solution</title>
 <link>http://qedcode.com/practice/socket/solution</link>
 <description>&lt;p&gt;Two weeks ago, I assigned &lt;a href="http://adventuresinsoftware.com/blog/?p=440"&gt;homework&lt;/a&gt;. Rewrite the .NET Socket API so that you can prove the following assertions:
&lt;ul&gt;
&lt;li&gt;You cannot use a Socket returned from Accept to accept any additional connections from the connection queue.
&lt;/li&gt;&lt;li&gt;You cannot call Accept, Bind, Connect, Listen, Receive, or Send if the socket has been closed.
&lt;/li&gt;&lt;li&gt;You must call Bind before you can call the Listen method.
&lt;/li&gt;&lt;li&gt;You must call Listen before calling Accept.
&lt;/li&gt;&lt;li&gt;Connect(string host, int port) can only be called if addressFamily is either InterNetwork or InterNetworkV6.
&lt;/li&gt;&lt;li&gt;Connect cannot be called if Listen has been called.
&lt;/li&gt;&lt;li&gt;You have to either call Connect or Accept before Sending and Receiving data.
&lt;/li&gt;&lt;li&gt;If the socket has been previously disconnected, then you cannot use Connect to restore the connection. &lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;&lt;p&gt; These assertions are prominently listed in the MSDN documentation. Why not roll them into the API itself? Let the compiler prove that we are using sockets correctly. Last week, I gave you a &lt;a href="http://adventuresinsoftware.com/blog/?p=445"&gt;hint&lt;/a&gt;. I moved the Send and Receive methods out to a different class so that we can prove that you've called Accept or Connect prior to Send or Receive. Both Accept and Connect became factory methods. You must call the factory before you get the object, and you must get the object before you call its methods. Q.E.D. Let's start from there and prove the rest of the assertions. &lt;strong&gt;Starting point&lt;/strong&gt;
&lt;ul&gt;
&lt;li&gt;You have to either call Connect or Accept before Sending and Receiving data. &lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;public class ConnectedSocket
{
    public int Receive(byte[] buffer);
    public int Send(byte[] buffer);
}

public class Socket : IDisposable
{
    public Socket(SocketInformation socketInformation);
    public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);

    public ConnectedSocket Accept();
    public void Bind(EndPoint localEP);
    public ConnectedSocket Connect(EndPoint remoteEP);
    public ConnectedSocket Connect(string host, int port);
    public void Dispose();
    public void Listen(int backlog);
}&lt;/pre&gt;&lt;/p&gt;&lt;p&gt;Looking through the list of assertions, we find that this one is already taken care of by the first change:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You cannot use a Socket returned from Accept to accept any additional connections from the connection queue. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;The ConnectedSocket class doesn't have an Accept method, so you can't call it. Q.E.D.&lt;br /&gt;
&lt;strong&gt;Other prerequisites&lt;/strong&gt;There are three other prerequisite assertions that we can prove in exactly the same way:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You must call Bind before you can call the Listen method.
&lt;/li&gt;&lt;li&gt;You must call Listen before calling Accept.
&lt;/li&gt;&lt;li&gt;Connect cannot be called if Listen has been called. &lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;public class Socket : IDisposable
{
    public Socket(SocketInformation socketInformation);
    public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);

    public &lt;strong&gt;BoundSocket&lt;/strong&gt; Bind(EndPoint localEP);
    public ConnectedSocket Connect(EndPoint remoteEP);
    public ConnectedSocket Connect(string host, int port);
    public void Dispose();
}

public class BoundSocket
{
    public ListeningSocket Listen(int backlog);
    public ConnectedSocket Connect(EndPoint remoteEP);
    public ConnectedSocket Connect(string host, int port);
}

public class ListeningSocket
{
    public ConnectedSocket Accept();
}&lt;/pre&gt;&lt;p&gt;Bind becomes a factory for the class that gives you Listen. Bind does not take away your ability to call Connect. Listen does.&lt;br /&gt;
&lt;strong&gt;Factory and product&lt;/strong&gt;Factories are great prerequisites. Now that it is becoming more obvious that we are using that pattern, let's rename Socket and move IDisposable to the product.&lt;/p&gt;
&lt;pre&gt;public class &lt;strong&gt;SocketFactory&lt;/strong&gt;
{
    public SocketFactory(SocketInformation socketInformation);
    public SocketFactory(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);

    public BoundSocket Bind(EndPoint localEP);
    public ConnectedSocket Connect(EndPoint remoteEP);
    public ConnectedSocket Connect(string host, int port);
}

public class ConnectedSocket : &lt;strong&gt;IDisposable&lt;/strong&gt;
{
    public int Receive(byte[] buffer);
    public int Send(byte[] buffer);
    public void Dispose();
}&lt;/pre&gt;&lt;p&gt;The ConnectedSocket is the ultimate product. That's the socket that needs to be closed. And what do you know, this change proves another of our assertions:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;If the socket has been previously disconnected, then you cannot use Connect to restore the connection. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;It is impossible to call Connect on a socket that has been disposed, since they aren't the same object anymore.&lt;br /&gt;
&lt;strong&gt;Dispose once&lt;/strong&gt;Now that the Dispose method is where it belongs, let's focus on the assertion most concerned with its use:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You cannot call Accept, Bind, Connect, Listen, Receive, or Send if the socket has been closed. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Accept, Bind, Connect, and Listen have already been taken care of, since they have become factory methods. To handle Send and Receive, we turn every ConnectedSocket factory into a callback:&lt;/p&gt;
&lt;pre&gt;public class ConnectedSocket
{
    public int Receive(byte[] buffer);
    public int Send(byte[] buffer);
}

public &lt;strong&gt;void&lt;/strong&gt; Connect(string host, int port, &lt;strong&gt;Action&amp;lt;ConnectedSocket&amp;gt;&lt;/strong&gt; action);&lt;/pre&gt;&lt;p&gt;We have taken away the capability of disposing a socket. The factory does it on the consumer's behalf. Since there is no way for the consumer to call Dispose, and since the callback returns before Dispose is called, there is no way to call Send or Receive after Dispose. Q.E.D.&lt;br /&gt;
&lt;strong&gt;Specialized factory&lt;/strong&gt;Which leaves us with one final assertion:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;Connect(string host, int port) can only be called if addressFamily is either InterNetwork or InterNetworkV6. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Again, we want to move the restricted method into its own special class. But now, we want to enforce that certain values are provided, not that certain methods are called. We'll limit this by creating our own smaller enumeration.&lt;/p&gt;
&lt;pre&gt;public class IPSocketFactory : SocketFactory
{
    public enum Version { V4, V6 }
    public IPSocketFactory(&lt;strong&gt;Version version&lt;/strong&gt;, SocketType socketType, ProtocolType protocolType)
        : base(
            version == Version.V4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6,
            socketType,
            protocolType) { }

    public void Connect(string host, int port, Action&amp;lt;ConnectedSocket&amp;gt; action);
}&lt;/pre&gt;&lt;p&gt;If you want to call the Connect overload with two parameters, you have to use the limited enumeration to get the right factory. I didn't mess with the overloaded constructor, because it complicates things.&lt;br /&gt;
One slight wrinkle. In a previous change we created a copy of the Connect method, since it can be called after Bind(). So we make the same change there:&lt;/p&gt;
&lt;pre&gt;public class IPBoundSocket : BoundSocket
{
    public void Connect(string host, int port, Action&amp;lt;ConnectedSocket&amp;gt; action);
}

public class IPSocketFactory : SocketFactory
{
    public enum Version { V4, V6 }
    public IPSocketFactory(Version version, SocketType socketType, ProtocolType protocolType)
        : base(
            version == Version.V4 ? AddressFamily.InterNetwork : AddressFamily.InterNetworkV6,
            socketType,
            protocolType) { }

    public &lt;strong&gt;IPBoundSocket&lt;/strong&gt; Bind(EndPoint localEP);
    public void Connect(string host, int port, Action&amp;lt;ConnectedSocket&amp;gt; action);
}&lt;/pre&gt;&lt;p&gt;The only way to get an IPBoundSocket is to use the IPSocketFactory. Therefore, you must have selected one of the Internet protocols. By the way, this is taking advantage of a little-used feature of C# called covarience. This is the one part of the proof that might not work in other languages.&lt;br /&gt;
So there you have it. A provably correct Socket API. There is no way to use it incorrectly. The compiler enforces all of the assertions that we would otherwise have to read the documentation to discover.&lt;/p&gt;
</description>
 <comments>http://qedcode.com/practice/socket/solution#comments</comments>
 <pubDate>Sun, 11 Oct 2009 04:18:14 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">15 at http://qedcode.com</guid>
</item>
<item>
 <title>Hint</title>
 <link>http://qedcode.com/practice/socket/hint</link>
 <description>&lt;p&gt;Your homework is extended for another week, but let me give you a hint what I'm looking for. The problem was to &lt;a href="http://adventuresinsoftware.com/blog/?p=440"&gt;Fix the Socket API&lt;/a&gt;. Rewrite the .NET Socket interface so that the assertions made in the MSDN documentation can be proven. To give you an example of what I'm looking for, take the following assertion:
&lt;ul&gt;
&lt;li&gt;You have to either call Connect or Accept before Sending and Receiving data. &lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;&lt;p&gt; This is a prerequisite assertion. We must first call Connect or Accept, then we can call Send or Receive. To prove this assertion, I'll use factory methods. Here's the original Socket class:&lt;/p&gt;
&lt;pre&gt;public class Socket : IDisposable
{
    public Socket(SocketInformation socketInformation);
    public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);

    public Socket Accept();
    public void Bind(EndPoint localEP);
    public void Connect(EndPoint remoteEP);
    public void Connect(string host, int port);
    public void Dispose();
    public void Listen(int backlog);
    public int Receive(byte[] buffer);
    public int Send(byte[] buffer);
}&lt;/pre&gt;&lt;p&gt;Move the Send and Receive methods out of this class. We cannot call them yet. Move them into a new class called ConnectedSocket.&lt;/p&gt;
&lt;pre&gt;public class ConnectedSocket
{
    public int Receive(byte[] buffer);
    public int Send(byte[] buffer);
}&lt;/pre&gt;&lt;p&gt;To prove that we have to call Connect or Accept before any of the ConnectedSocket methods, we make Connect and Accept factory methods:&lt;/p&gt;
&lt;pre&gt;public class Socket : IDisposable
{
    public Socket(SocketInformation socketInformation);
    public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);

    public &lt;strong&gt;ConnectedSocket&lt;/strong&gt; Accept();
    public void Bind(EndPoint localEP);
    public &lt;strong&gt;ConnectedSocket&lt;/strong&gt; Connect(EndPoint remoteEP);
    public &lt;strong&gt;ConnectedSocket&lt;/strong&gt; Connect(string host, int port);
    public void Dispose();
    public void Listen(int backlog);
}&lt;/pre&gt;&lt;p&gt;This API proves one of the assertions in the MSDN documentation. Try the others on your own. Answers will be posted next week.&lt;/p&gt;
</description>
 <comments>http://qedcode.com/practice/socket/hint#comments</comments>
 <pubDate>Sun, 11 Oct 2009 04:17:27 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">14 at http://qedcode.com</guid>
</item>
<item>
 <title>Socket API</title>
 <link>http://qedcode.com/practice/socket</link>
 <description>&lt;p&gt;Your task is to fix the .NET Socket API. This is as unhelpful as an API gets. There are several rules that a user of a Socket must follow. Create an API that proves that they are following all of the rules. Here is the relevant part of the existing unhelpful API:&lt;/p&gt;
&lt;pre&gt;public class Socket : IDisposable
{
    public Socket(SocketInformation socketInformation);
    public Socket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType);

    public Socket Accept();
    public void Bind(EndPoint localEP);
    public void Connect(EndPoint remoteEP);
    public void Connect(string host, int port);
    public void Dispose();
    public void Listen(int backlog);
    public int Receive(byte[] buffer);
    public int Send(byte[] buffer);
}&lt;/pre&gt;&lt;p&gt;Here are the rules as documented in MSDN:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You cannot use a Socket returned from Accept to accept any additional connections from the connection queue.
&lt;/li&gt;&lt;li&gt;You cannot call Accept, Bind, Connect, Listen, Receive, or Send if the socket has been closed.
&lt;/li&gt;&lt;li&gt;You must call Bind before you can call the Listen method.
&lt;/li&gt;&lt;li&gt;You must call Listen before calling Accept.
&lt;/li&gt;&lt;li&gt;Connect(string host, int port) can only be called if addressFamily is either InterNetwork or InterNetworkV6.
&lt;/li&gt;&lt;li&gt;Connect cannot be called if Listen has been called.
&lt;/li&gt;&lt;li&gt;You have to either call Connect or Accept before Sending and Receiving data.
&lt;/li&gt;&lt;li&gt;If the socket has been previously disconnected, then you cannot use Connect to restore the connection. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;You may use as the basis of your proof the concepts that were discussed in previous Q.E.D. articles, including:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;&lt;a href="http://adventuresinsoftware.com/blog/?p=410"&gt;Math 101 for developers&lt;/a&gt;
&lt;/li&gt;&lt;li&gt;&lt;a href="http://adventuresinsoftware.com/blog/?p=415"&gt;Proving prerequisites&lt;/a&gt;
&lt;/li&gt;&lt;li&gt;&lt;a href="http://adventuresinsoftware.com/blog/?p=416"&gt;The constructor: the strongest of all methods&lt;/a&gt;
&lt;/li&gt;&lt;li&gt;&lt;a href="http://adventuresinsoftware.com/blog/?p=429"&gt;Closure&lt;/a&gt;
&lt;/li&gt;&lt;li&gt;&lt;a href="http://adventuresinsoftware.com/blog/?p=432"&gt;Proof based on imperative programming&lt;/a&gt;
&lt;/li&gt;&lt;li&gt;&lt;a href="http://adventuresinsoftware.com/blog/?p=436"&gt;Fixing an unhelpful API&lt;/a&gt; &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;Please post responses in the comments, email them to &lt;a href="mailto:mperry@adventuresinsoftware.com"&gt;mperry@adventuresinsoftware.com&lt;/a&gt;, or post links on your own blog. I will share my solution next week.&lt;/p&gt;
</description>
 <comments>http://qedcode.com/practice/socket#comments</comments>
 <pubDate>Sun, 11 Oct 2009 04:16:45 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">13 at http://qedcode.com</guid>
</item>
<item>
 <title>Better solution</title>
 <link>http://qedcode.com/practice/cache/better-solution</link>
 <description>&lt;p&gt;The solution left the cache too constraining. While it was correct, it was too tightly locked. All users of the class will line up behind one another, whether they are after the same data or not.&lt;/p&gt;
&lt;p&gt;To resolve this problem, let's move the lock. Instead of locking on the cache while fetching the value, let's lock on the key. Two clients accessing the cache with the same key will line up, but clients with different keys will not.&lt;/p&gt;
&lt;p&gt;But we can't lock on the key itself. We need to lock on something with identity. The identity of the key is not important. A client can create a new instance of the key having the same value, and that should qualify as the same key. So we have to look elsewhere.&lt;/p&gt;
&lt;p&gt;Fortunately, the value of the key is used to find an object in the dictionary. That object &lt;em&gt;does&lt;/em&gt; have identity. So we move the lock there.&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; CachedObject&amp;lt;TValue&amp;gt;
{
    &lt;span style="color: blue"&gt;private&lt;/span&gt; TValue _value;
    &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;bool&lt;/span&gt; _fetched = &lt;span style="color: maroon"&gt;false&lt;/span&gt;;
    &lt;span style="color: blue"&gt;public&lt;/span&gt; DateTime DateCached { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public&lt;/span&gt; CachedObject(DateTime dateCached)
    {
        DateCached = dateCached;
    }

    &lt;span style="color: blue"&gt;public&lt;/span&gt; TValue Value
    {
        &lt;span style="color: blue"&gt;get&lt;/span&gt; { &lt;span style="color: blue"&gt;return&lt;/span&gt; _value; }
        &lt;span style="color: blue"&gt;set&lt;/span&gt; { _value = value; _fetched = &lt;span style="color: maroon"&gt;true&lt;/span&gt;; }
    }

    &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;bool&lt;/span&gt; Fetched
    {
        &lt;span style="color: blue"&gt;get&lt;/span&gt; { &lt;span style="color: blue"&gt;return&lt;/span&gt; _fetched; }
    }
}

&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; Cache&amp;lt;TKey, TValue&amp;gt;
{
    &lt;span style="color: blue"&gt;private&lt;/span&gt; TimeSpan _expiry;
    &lt;span style="color: blue"&gt;private&lt;/span&gt; Dictionary&amp;lt;TKey, CachedObject&amp;lt;TValue&amp;gt;&amp;gt; _store =
        &lt;span style="color: blue"&gt;new&lt;/span&gt; Dictionary&amp;lt;TKey, CachedObject&amp;lt;TValue&amp;gt;&amp;gt;();

    &lt;span style="color: blue"&gt;public&lt;/span&gt; Cache(TimeSpan expiry)
    {
        _expiry = expiry;
    }

    &lt;span style="color: blue"&gt;public&lt;/span&gt; TValue Get(TKey key, Func&amp;lt;TKey, TValue&amp;gt; fetch)
    {
        CachedObject&amp;lt;TValue&amp;gt; found;

        &lt;span style="color: blue"&gt;lock&lt;/span&gt; (_store)
        {
            &lt;span style="color: green"&gt;// If the object is not in the cache, or it is expired,&lt;/span&gt;
            &lt;span style="color: green"&gt;// fetch it and add it to the cache.&lt;/span&gt;
            DateTime now = DateTime.Now;
            &lt;span style="color: blue"&gt;if&lt;/span&gt; (_store.TryGetValue(key, &lt;span style="color: blue"&gt;out&lt;/span&gt; found) &amp;amp;&amp;amp;
                found.DateCached + _expiry &amp;lt; now)
            {
                &lt;span style="color: blue"&gt;return&lt;/span&gt; found.Value;
            }

            found = &lt;span style="color: blue"&gt;new&lt;/span&gt; CachedObject&amp;lt;TValue&amp;gt;(now);
            _store.Add(key, found);
        }

        &lt;span style="color: blue"&gt;lock&lt;/span&gt; (found)
        {
            &lt;span style="color: blue"&gt;if&lt;/span&gt; (!found.Fetched)
                found.Value = fetch(key);
            &lt;span style="color: blue"&gt;return&lt;/span&gt; found.Value;
        }
    }
}&lt;/pre&gt;&lt;p&gt;The Get method locks first on the cache. This protects the data structure, and ensures that we get just one instance of CachedObject. Once it has that, it locks on the found CachedObject so that clients after the same key line up.&lt;/p&gt;
&lt;p&gt;Inside the lock, it checks to see whether the value has already been fetched. If not, this thread is the first in line, so it fetches the value. But if it &lt;em&gt;has&lt;/em&gt; already been fetched, then the thread was not the first in line and can just use the fetched object.&lt;/p&gt;
&lt;p&gt;The above is not a formal proof, and has many logical holes. Hopefully we'll have time to shore it up, and possibly find bugs in the code along the way. This is the kind of code that definitely needs to be proven. Sure, unit testing can give us some confidence, but no amount of unit testing can verify that this code is completely thread safe.&lt;/p&gt;
</description>
 <comments>http://qedcode.com/practice/cache/better-solution#comments</comments>
 <pubDate>Sun, 11 Oct 2009 04:16:06 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">12 at http://qedcode.com</guid>
</item>
<item>
 <title>Cache</title>
 <link>http://qedcode.com/practice/cache</link>
 <description>&lt;p&gt;Given this source code for a cache, rewrite the API to prove that a race condition cannot occur:&lt;br /&gt;&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; CachedObject&amp;lt;TValue&amp;gt;
{
    &lt;span style="color: blue"&gt;public&lt;/span&gt; TValue Value { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }
    &lt;span style="color: blue"&gt;public&lt;/span&gt; DateTime DateCached { &lt;span style="color: blue"&gt;get&lt;/span&gt;; &lt;span style="color: blue"&gt;private&lt;/span&gt; &lt;span style="color: blue"&gt;set&lt;/span&gt;; }

    &lt;span style="color: blue"&gt;public&lt;/span&gt; CachedObject(TValue value, DateTime dateCached)
    {
        Value = value;
        DateCached = dateCached;
    }
}

&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; Cache&amp;lt;TKey, TValue&amp;gt;
{
    &lt;span style="color: blue"&gt;private&lt;/span&gt; TimeSpan _expiry;
    &lt;span style="color: blue"&gt;private&lt;/span&gt; Dictionary&amp;lt;TKey, CachedObject&amp;lt;TValue&amp;gt;&amp;gt; _store =
        &lt;span style="color: blue"&gt;new&lt;/span&gt; Dictionary&amp;lt;TKey, CachedObject&amp;lt;TValue&amp;gt;&amp;gt;();

    &lt;span style="color: blue"&gt;public&lt;/span&gt; Cache(TimeSpan expiry)
    {
        _expiry = expiry;
    }

    &lt;span style="color: blue"&gt;public&lt;/span&gt; TValue Get(TKey key)
    {
        CachedObject&amp;lt;TValue&amp;gt; found;

        &lt;span style="color: green"&gt;// If the object is in the cache, check the date.&lt;/span&gt;
        &lt;span style="color: blue"&gt;if&lt;/span&gt; (_store.TryGetValue(key, &lt;span style="color: blue"&gt;out&lt;/span&gt; found) &amp;amp;&amp;amp;
            found.DateCached + _expiry &amp;lt; DateTime.Now)
        {
            &lt;span style="color: blue"&gt;return&lt;/span&gt; found.Value;
        }
        &lt;span style="color: blue"&gt;else&lt;/span&gt;
        {
            &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;default&lt;/span&gt;(TValue);
        }
    }

    &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; Put(TKey key, TValue value)
    {
        _store.Add(key, &lt;span style="color: blue"&gt;new&lt;/span&gt; CachedObject&amp;lt;TValue&amp;gt;(value, DateTime.Now));
    }
}&lt;/pre&gt;&lt;p&gt;The caller has to use it properly for it to work. They have to call Get before Put (prerequisite), and they have to synchronize around the two calls. If they don't, they run the risk of creating a race condition.&lt;/p&gt;
&lt;p&gt;A race condition occurs when the outcome of an operation depends upon other operations happening in parallel. If one thread gets finished first, there is one result. If another thread finishes first, there is another. In this case, two threads could try to Get the same value. Finding none, they can both race to fetch the value and put it in the cache.&lt;/p&gt;
&lt;p&gt;Rewrite this API to prove that a race condition cannot occur.&lt;/p&gt;
</description>
 <comments>http://qedcode.com/practice/cache#comments</comments>
 <pubDate>Sun, 11 Oct 2009 04:15:16 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">11 at http://qedcode.com</guid>
</item>
<item>
 <title>Fixing an unhelpful API</title>
 <link>http://qedcode.com/practice/service/fixing-an-unhelpful-api</link>
 <description>&lt;p&gt;Prove the correctness of a service. Here is how it started:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; DoWorkWithOrderService()
{
    &lt;span style="color: blue"&gt;using&lt;/span&gt; (ITransaction currentTransaction = &lt;span style="color: blue"&gt;new&lt;/span&gt; AcidTransaction(_container))
    {
        OrderService.Transaction = currentTransaction;
        OrderService.DoWork();
        currentTransaction.Commit();
    }
}&lt;/pre&gt;&lt;p&gt;It is only possible to prove the correctness of this code based on the caller (seen here), and not the order service itself. If the caller forgets to initialize the transaction property, if the caller forgets to create the transaction in a using statement, or if the caller forgets to create a new instance per thread, then bad things can happen.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://adventuresinsoftware.com/blog/wp-content/uploads/2009/09/unhelpful-api.jpg"&gt;&lt;img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" border="0" alt="Unhelpful_API" align="right" src="http://adventuresinsoftware.com/blog/wp-content/uploads/2009/09/unhelpful-api-thumb.jpg" width="244" height="133" /&gt;&lt;/a&gt; The order service is an unhelpful API. When you approach it, you have to use caution. If you use it in the wrong way, bad things will happen. If you're lucky, it will throw an exception. If you are unlucky, you won't catch errors until you release to production.&lt;/p&gt;
&lt;p&gt;An unhelpful API must be approached with fear.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Parameters are prerequisites&lt;/strong&gt;&lt;br /&gt;The first step in improving this unhelpful API is to ensure that a transaction exists before a service method is called. We can do this by turning the property into a parameter.&lt;/p&gt;
&lt;p&gt;Before:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; Service : IService
{
    &lt;span style="color: blue"&gt;public&lt;/span&gt; ITransaction Transaction
    {
        &lt;span style="color: blue"&gt;set&lt;/span&gt;;
        &lt;span style="color: blue"&gt;get&lt;/span&gt;;
    }
    
    &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; DoWork() { }
}&lt;/pre&gt;&lt;p&gt;After:&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; ServiceFactory : IServiceFactory
{
    &lt;span style="color: blue"&gt;public&lt;/span&gt; IService CreateService(ITransaction transaction)
    {
        &lt;span style="color: blue"&gt;return&lt;/span&gt; &lt;span style="color: blue"&gt;new&lt;/span&gt; Service(transaction);
    }
}

&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; Service : IService
{
    &lt;span style="color: blue"&gt;private&lt;/span&gt; ITransaction _transaction;
    
    &lt;span style="color: blue"&gt;public&lt;/span&gt; Service(ITransaction transaction)
    {
        _transaction = transaction;
    }
    
    &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; DoWork() { }
}&lt;/pre&gt;&lt;p&gt;You cannot get a service from the factory without providing a transaction. Therefore, you cannot make any service calls before providing a transaction. Q.E.D.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Callbacks are prerequisites&lt;/strong&gt;&lt;br /&gt;We have proven that a transaction is provided before a service method is called, but we haven't yet proven that the transaction gets disposed. We can take one more step toward making this a helpful, provable API using a callback.&lt;/p&gt;
&lt;pre&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;class&lt;/span&gt; ServiceFactory : IServiceFactory
{
    &lt;span style="color: blue"&gt;private&lt;/span&gt; ITransactionFactory _transactionFactory;

    &lt;span style="color: blue"&gt;public&lt;/span&gt; &lt;span style="color: blue"&gt;void&lt;/span&gt; CallService(Action&amp;lt;IService&amp;gt; action)
    {
        &lt;span style="color: blue"&gt;using&lt;/span&gt; (ITransaction transaction =
            _transactionFactory.CreateTransaction())
        {
            action(&lt;span style="color: blue"&gt;new&lt;/span&gt; Service(transaction));
        }
    }
}&lt;/pre&gt;&lt;p&gt;A transaction factory is injected into the service factory (via constructor not shown here), and that is used to create a transaction as needed. That creation happens within a using statement in the service factory, not in the calling code. There is no way for the caller to forget to do this. Thus we have proven that the transaction gets disposed.&lt;/p&gt;
&lt;p&gt;In these two steps, we have transformed an unhelpful API into a helpful one. The unhelpful API offered many options, most of them wrong. The helpful API offers only the options that are correct. It guides the caller in its proper use. It cannot be used incorrectly.&lt;/p&gt;
&lt;p&gt;An unhelpful API cannot be proven. It must be approached with fear. A helpful API can be proven. It can be approached with confidence.&lt;/p&gt;
</description>
 <comments>http://qedcode.com/practice/service/fixing-an-unhelpful-api#comments</comments>
 <pubDate>Sun, 11 Oct 2009 04:13:46 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">10 at http://qedcode.com</guid>
</item>
<item>
 <title>Service transaction</title>
 <link>http://qedcode.com/practice/service</link>
 <description>&lt;p&gt;Below is the source code for a service. Prove that:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;The service has a transaction when it is called.
&lt;/li&gt;&lt;li&gt;The transaction is disposed.
&lt;/li&gt;&lt;li&gt;The code is thread safe. &lt;/li&gt;
&lt;/ul&gt;
&lt;pre&gt;&lt;span style="color: blue"&gt;public&lt;/span&gt; Order GetOrder(&lt;span style="color: blue"&gt;int&lt;/span&gt; orderId)
{
   &lt;span style="color: blue"&gt;return&lt;/span&gt; InvokeGetOrder(() =&amp;gt; OrderServiceProvider.GetOrderWithItems(orderId));
}

&lt;span style="color: blue"&gt;public&lt;/span&gt; Order InvokeGetOrder(Func&amp;lt;Order&amp;gt; function)
{
    Order order;
    &lt;span style="color: blue"&gt;using&lt;/span&gt; (IBusinessTransactionContext currentBusinessTransactionContext =
        &lt;span style="color: blue"&gt;new&lt;/span&gt; AcidBusinessTransactionContext(_container, &lt;span style="color: maroon"&gt;false&lt;/span&gt;))
    {
        OrderServiceProvider.BusinessTransactionContext =
            currentBusinessTransactionContext;

        order = function();
        OrderServiceProvider.BusinessTransactionContext.Commit();
    }

    &lt;span style="color: blue"&gt;return&lt;/span&gt; order;
}&lt;/pre&gt;</description>
 <comments>http://qedcode.com/practice/service#comments</comments>
 <pubDate>Sun, 11 Oct 2009 04:12:47 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">9 at http://qedcode.com</guid>
</item>
<item>
 <title>Correct the induction problem</title>
 <link>http://qedcode.com/practice/movement/correction</link>
 <description>&lt;p&gt;Let's take another run at proving that a watch movement with 20 parts has 19 connections.&lt;/p&gt;
&lt;p&gt;&lt;a href="http://adventuresinsoftware.com/blog/wp-content/uploads/2009/09/sixgears.jpg"&gt;&lt;img style="border-right-width: 0px; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" border="0" alt="SixGears" align="right" src="http://adventuresinsoftware.com/blog/wp-content/uploads/2009/09/sixgears-thumb.jpg" width="235" height="169" /&gt;&lt;/a&gt; It is difficult to prove that any movement can be constructed one gear at a time by making just one connection with an existing gear. And here is a counter-example to demonstrate the problem.&lt;/p&gt;
&lt;p&gt;A ring of six gears, all the same size, is a movement with one degree of freedom. If you construct this movement one gear at a time, you will connect the final gear to two prior components, not to just one. This movement has 6 gears and 6 connections, not the 5 that we want our proof to show.&lt;/p&gt;
&lt;p&gt;Something is obviously wrong here. This movement is not what is intended by the problem, but it is not explicitly prohibited either. We need to change the problem:&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Given:&lt;/strong&gt; A movement with 20 moving parts having one degree of freedom &lt;strong&gt;&lt;em&gt;and no redundant connections&lt;/em&gt;&lt;/strong&gt;.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Prove: &lt;/strong&gt;There are 19 connections among those parts.&lt;/p&gt;
&lt;p&gt;Now our problem is precise enough. While it may seem wrong to change a problem in order to solve it, this is something that happens all the time in software. The requirements are never stated precisely. We always have to go back and ask questions. In the process, we refine the definition of the problem until we agree on something that can be implemented unambiguously.&lt;/p&gt;
&lt;p&gt;&lt;strong&gt;Find a new induction&lt;/strong&gt;&lt;br /&gt;After changing our problem to make it provable, we still find that our original approach is difficult. In order to prove that any valid movement can be built on part at a time, we have to prove that there is always at least one component connected to only one neighbor. We have to prove the existence of a leaf.&lt;/p&gt;
&lt;p&gt;While this is not a terribly difficult proof, there is an easier way. We could choose a less restrictive induction. Rather than assuming that we can build a movement one part at a time, we only need to know that we can build any movement from two smaller movements. This satisfies the requirements of inductive reasoning.&lt;/p&gt;
&lt;p&gt;So first, to prove that we can construct any movement from two smaller movements, we just need to select any connection within the movement. Now break this connection. One of two things will happen:&lt;/p&gt;
&lt;ul&gt;
&lt;li&gt;You are left with one movement, in which case the connection was redundant. The larger movement was invalid and therefore not covered by the proof.
&lt;/li&gt;&lt;li&gt;You are left with two movements, each with one degree of freedom. Since we broke only one connection, the others remain intact. Assuming the larger movement had no redundant connections, neither do the smaller ones. &lt;/li&gt;
&lt;/ul&gt;
&lt;p&gt;So the process of building a movement out of smaller movements is valid. Now we can write our proof:&lt;/p&gt;
&lt;ol&gt;
&lt;li&gt;Let M&lt;sub&gt;j+k&lt;/sub&gt; be the movement formed by connecting M&lt;sub&gt;j&lt;/sub&gt; and M&lt;sub&gt;k&lt;/sub&gt;.
&lt;/li&gt;&lt;li&gt;g(M&lt;sub&gt;j+k&lt;/sub&gt;) = g(M&lt;sub&gt;j&lt;/sub&gt;) + g(M&lt;sub&gt;k&lt;/sub&gt;), because we combined two sets of gears.
&lt;/li&gt;&lt;li&gt;c(M&lt;sub&gt;j+k&lt;/sub&gt;) = c(M&lt;sub&gt;j&lt;/sub&gt;) + c(M&lt;sub&gt;k&lt;/sub&gt;) + 1, because we added only one new connection.
&lt;/li&gt;&lt;li&gt;c(M&lt;sub&gt;j+k&lt;/sub&gt;) = g(M&lt;sub&gt;j&lt;/sub&gt;)-1 + g(M&lt;sub&gt;k&lt;/sub&gt;)-1 + 1, by applying the assumption of the induction.
&lt;/li&gt;&lt;li&gt;c(M&lt;sub&gt;j+k&lt;/sub&gt;) = g(M&lt;sub&gt;j&lt;/sub&gt;) + g(M&lt;sub&gt;k&lt;/sub&gt;) - 1, by association.
&lt;/li&gt;&lt;li&gt;c(M&lt;sub&gt;j+k&lt;/sub&gt;) = g(M&lt;sub&gt;j+k&lt;/sub&gt;) - 1, by combining 2 and 5. &lt;/li&gt;
&lt;/ol&gt;
&lt;p&gt;Q.E.D.&lt;/p&gt;
</description>
 <pubDate>Sun, 11 Oct 2009 04:10:08 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">8 at http://qedcode.com</guid>
</item>
<item>
 <title>Inductive reasoning</title>
 <link>http://qedcode.com/practice/movement/inductive-reasoning</link>
 <description>&lt;p&gt;The problem was: &lt;strong&gt;Given:&lt;/strong&gt; A movement with 20 moving parts having one degree of freedom. &lt;strong&gt;Prove: &lt;/strong&gt;There are ___ connections among those parts. The answer, of course, is 19. But the real exercise is in the proof. This problem is solvable using a technique called inductive reasoning. Inductive reasoning is proving a statement in two parts. First, you prove it for a trivial case. Then, you prove that if it's true for a smaller case, it must be true for a larger case. &lt;strong&gt;State the problem&lt;/strong&gt;To begin, we need to define some terms to help us reason about the problem. We'll define the terms M, g(M), and c(M) like this:
&lt;ul&gt;
&lt;li&gt;Let M be a movement with one degree of freedom.
&lt;/li&gt;&lt;li&gt;Let g(M) be the number of gears in the movement.
&lt;/li&gt;&lt;li&gt;Let c(M) be the number of connections in the movement.&lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;&lt;p&gt; Using these terms, we can state the problem as:
&lt;ul&gt;
&lt;li&gt;Proove that c(M) = g(M)-1.&lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;&lt;p&gt; &lt;strong&gt;Start with the trivial&lt;/strong&gt;The trivial case is a movement having a single gear. This movement has no connections, since there are no other gears to which it can connect. Written using our new terms:
&lt;ul&gt;
&lt;li&gt;Let M0 be a movement having only one gear.
&lt;/li&gt;&lt;li&gt;g(M0) = 1.
&lt;/li&gt;&lt;li&gt;c(M0) = 0.
&lt;/li&gt;&lt;li&gt;c(M0) = g(M0) - 1.&lt;/li&gt;
&lt;/ul&gt;
&lt;/p&gt;&lt;p&gt; &lt;strong&gt;Build upward&lt;/strong&gt;Now if I have a movement Mj, what happens when I add another gear to it? I end up with a movement Mj+1. I want to prove that the connections in Mj+1 are one fewer than the gears. Inductive reasoning lets me assume that this is true for Mj.
&lt;ol&gt;
&lt;li&gt;c(Mj) = g(Mj) - 1.
&lt;/li&gt;&lt;li&gt;g(Mj+1) = g(Mj) + 1, because I added a gear.
&lt;/li&gt;&lt;li&gt;c(Mj+1) = c(Mj) + 1, because I connected that gear to exactly one previous gear.
&lt;/li&gt;&lt;li&gt;c(Mj+1) = g(Mj) - 1 + 1, by combining steps 1 and 3.
&lt;/li&gt;&lt;li&gt;c(Mj+1) = g(Mj) + 1 - 1, by commuting step 4.
&lt;/li&gt;&lt;li&gt;c(Mj+1) = g(Mj+1) - 1, by combining steps 2 and 5.&lt;/li&gt;
&lt;/ol&gt;
&lt;/p&gt;&lt;p&gt; Q.E.D. &lt;strong&gt;Not so fast&lt;/strong&gt;I was imprecise in my reasoning in a few places. While this still led to the correct answer in this case, it might have led to something completely wrong in a different problem. Inductive reasoning requires that you prove that the steps you take to get from a smaller problem to a bigger one will cover all possible problems. You have to prove that you can build a movement one part at a time by connecting that gear to exactly one gear of the previous movement. While this is true, it is by no means obvious. If we can't prove that our induction can build any movement, then we can't use it to prove statements about all movements. What about those that can't be assembled one part at a time? What we need is a different induction, one that more obviously covers all movements.&lt;/p&gt;
</description>
 <comments>http://qedcode.com/practice/movement/inductive-reasoning#comments</comments>
 <pubDate>Sun, 11 Oct 2009 04:09:13 +0000</pubDate>
 <dc:creator>Michael L Perry</dc:creator>
 <guid isPermaLink="false">7 at http://qedcode.com</guid>
</item>
</channel>
</rss>
