<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Solutionizing .NET &#187; F#</title>
	<atom:link href="http://solutionizing.net/category/f/feed/" rel="self" type="application/rss+xml" />
	<link>http://solutionizing.net</link>
	<description>Random thoughts on custom development in SharePoint.</description>
	<lastBuildDate>Sat, 12 May 2012 03:45:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='solutionizing.net' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Solutionizing .NET &#187; F#</title>
		<link>http://solutionizing.net</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://solutionizing.net/osd.xml" title="Solutionizing .NET" />
	<atom:link rel='hub' href='http://solutionizing.net/?pushpress=hub'/>
		<item>
		<title>TextReader.TryReadLine And Idiomatic Code</title>
		<link>http://solutionizing.net/2009/05/05/textreader-tryreadline-and-idiomatic-code/</link>
		<comments>http://solutionizing.net/2009/05/05/textreader-tryreadline-and-idiomatic-code/#comments</comments>
		<pubDate>Tue, 05 May 2009 13:41:58 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[idiomatic code]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=412</guid>
		<description><![CDATA[Today I reread a post by Eric Lippert on High Maintenance code. It&#8217;s an interesting read in general, but some of the comments got me thinking about idioms in code. The discussion started with this bit of C#: string line; while ((line = reader.ReadLine()) != null)     yield return line; A familiar pattern in C [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=412&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Today I reread a post by <a href="http://blogs.msdn.com/ericlippert/default.aspx">Eric Lippert</a> on <a title="High Maintenance" href="http://blogs.msdn.com/ericlippert/archive/2008/09/08/high-maintenance.aspx">High Maintenance</a> code. It&#8217;s an interesting read in general, but some of the comments got me thinking about idioms in code. The discussion started with this bit of C#:</p>
<pre><span class="code">string line;</span>
<span class="code">while ((line = reader.ReadLine()) != null)
    yield return line;</span></pre>
<p>A familiar pattern in C and C++, but it just doesn&#8217;t feel right for C#. Eric cites this is a flaw &#8220;because it tries to do so much in one line.&#8221; His rewrite uses the following instead:</p>
<pre>while (true)
{
    string line = reader.ReadLine();
    if (line == null)
        yield break;
    yield return line;
}</pre>
<p>While certainly easier to read, it still seems like a lot of work. Commenter <a href="http://www.sebastienlorion.com/">Sebastien Lorion</a> suggests  this is a flaw in the API: &#8220;&#8230;we would not need such a hack or the awkward code you posted if the method was better designed.&#8221; I&#8217;m not sure I agree—<code>ReadLine</code> implies the line read will be returned, and if there&#8217;s nothing to read then nothing (<code>null</code>) should be returned. Sebastien&#8217;s &#8220;better design&#8221; doesn&#8217;t make sense idiomatically; what he really wants is <code>TryReadLine</code>, which would closely match his suggested signature of <code>bool ReadLine(out string line)</code>. This strikes me as a perfect extension candidate:</p>
<pre>public static bool TryReadLine(this TextReader reader, out string line)
{
    line = reader.ReadLine();
    return line != null;
}</pre>
<p>With which we can write a more C#-idiomatic yet compact version of the original code:</p>
<pre>public static IEnumerable&lt;string&gt; GetLines(this TextReader reader)
{
    string line;
    while (reader.TryReadLine(out line))
        yield return line;
}</pre>
<p>Now one could argue whether or not <code>TryReadLine()</code> should catch the possible exceptions from <code>ReadLine()</code>, but that&#8217;s not the point. The point is that C# has an established pattern for methods that return a boolean indicating success in populating an <code>out</code> parameter, and code written as such is easier to read in a C# context.</p>
<p>It&#8217;s also interesting to note how the coding patterns can evolve with language features. For example, F# happens to have an <code>Option</code> type that aligns perfectly with this pattern: it either has <code>Some</code> value or is <code>None</code>. Paired with pattern matching, this presents a superior alternative to booleans and out parameters. So in idiomatic F# we would write <code>TryReadLine</code> like this instead:</p>
<pre>namespace System.IO
    [&lt;AutoOpen&gt;]
    module TextReaderExtensions
        type System.IO.TextReader with
            member r.TryReadLine() =
                match r.ReadLine() with
                | null  -&gt; None
                | line  -&gt; Some line</pre>
<p>Which could be used tail-recursively to fetch a sequences of lines:</p>
<pre>            member r.Lines =
                let rec lines_core (tr : TextReader) =
                    seq {
                        match tr.TryReadLine() with
                        | None   -&gt; yield! Seq.empty
                        | Some l -&gt; yield l; yield! lines_core tr
                    }
                lines_core r</pre>
<p>Eric ends his article with excellent advice: &#8220;Whenever you write a method <strong>think about the contract of that method</strong>.&#8221; As a corollary to that, whenever you write a method <strong>think about idioms that fit the method contract</strong>. An important part of maintainability is writing code that makes sense in the context of other code that has been written. Clever code that nobody can read isn&#8217;t particularly clever.</p>
<br /> Tagged: idiomatic code <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/412/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/412/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/412/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=412&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/05/05/textreader-tryreadline-and-idiomatic-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
		<item>
		<title>Elegant Inline Debug Tracing</title>
		<link>http://solutionizing.net/2009/04/14/elegant-inline-debug-tracing/</link>
		<comments>http://solutionizing.net/2009/04/14/elegant-inline-debug-tracing/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 04:37:33 +0000</pubDate>
		<dc:creator>Keith Dahlby</dc:creator>
				<category><![CDATA[.NET]]></category>
		<category><![CDATA[F#]]></category>
		<category><![CDATA[Object Model]]></category>
		<category><![CDATA[PowerShell]]></category>
		<category><![CDATA[SharePoint]]></category>
		<category><![CDATA[Debugging]]></category>
		<category><![CDATA[higher-order function]]></category>

		<guid isPermaLink="false">http://solutionizing.net/?p=500</guid>
		<description><![CDATA[As much fun as it is to step through code with a debugger, I usually prefer to use System.Diagnostics.Debug and Trace with DebugView to see what&#8217;s happening in realtime. This is particularly handy to track intermediate results in higher-order functions that you might not be able to step into. However, it&#8217;s not always convenient to [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=500&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>As much fun as it is to step through code with a debugger, I usually prefer to use <a title="Debug Class (System.Diagnostics)" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.aspx"><code>System.Diagnostics.Debug</code></a> and <a title="Trace Class (System.Diagnostics)" href="http://msdn.microsoft.com/en-us/library/system.diagnostics.trace.aspx"><code>Trace</code></a> with <a title="DebugView for Windows" href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx">DebugView</a> to see what&#8217;s happening in realtime. This is particularly handy to track intermediate results in higher-order functions that you might not be able to step into. However, it&#8217;s not always convenient to insert debugging statements amongst the composed expressions of F#, PowerShell or LINQ.</p>
<p>An alternative first came to mind while working in F#:</p>
<pre>let dbg x = System.Diagnostics.Debug.WriteLine(x |&gt; sprintf "%A"); x</pre>
<p>(Read <code>|&gt;</code> as &#8220;as next parameter to&#8221;.) We can then use this function anywhere to peek at a value, perhaps an intermediate list in this trivial example:</p>
<pre>let data = [1..10]
           |&gt; List.filter (fun i -&gt; i%3 = 0) |&gt; dbg
           |&gt; List.map (fun i -&gt; i*i)</pre>
<p>Indeed <code>[3; 6; 9]</code> are traced as multiples of three. Not a particularly convincing example, but it should be pretty easy to imagine a more complex algorithm for which unintrusive tracing would be useful.</p>
<p>This works pretty well with F#&#8217;s <code>|&gt;</code> operator to push values forward, but what about C#? Given my posting history, it shouldn&#8217;t be hard to guess where I&#8217;m going with this&#8230;</p>
<h3>Extension Methods</h3>
<p>So if <code>|&gt;</code> is &#8220;as next parameter to&#8221;, the <code>.</code> of an extension method call might read &#8220;as first parameter to&#8221;. So we can implement a roughly equivalent function (sans F#&#8217;s nice deep-print formatter <code>"%A"</code>) like so:</p>
<pre>    public static T Debug&lt;T&gt;(this T value)
    {
        Debug.WriteLine(value);
        return value;
    }

    public static T Dbg&lt;T&gt;(this T value, string category)
    {
        Debug.WriteLine(value, category);
        return value;
    }</pre>
<p><del datetime="2009-04-19T20:15:33+00:00">I find the optional label handy to keep different traces separate.</del> <ins datetime="2009-04-19T20:15:33+00:00">Looking again, there&#8217;s an overload that accepts a category, so we&#8217;ll use that instead.</ins> So why might this be useful? Maybe we want to log the value assigned within an object initializer:</p>
<pre>var q = new SPQuery() {
  Query = GetMyQuery().Debug("Query")
};</pre>
<p>Rather than store the query string to a temporary variable or retrieve the property after it&#8217;s been set, we can just trace the value inline. Or consider a LINQ example:</p>
<pre>var items = from SPListItem item in list.GetItems(q)
            let url = new SPFieldUrlValue(item["URL"] as string)
            where url.Url.Debug("URL").StartsWith(baseUrl, StringComparison.OrdinalIgnoreCase)
            select new
            {
                Title = item.Title.Debug("Title"),
                Description = url.Description,
            };</pre>
<p>Here we log all URLs that pass through, even the ones excluded from the result by the predicate. This would be much harder to implement efficiently without inline logging.</p>
<p>This technique works great for simple objects with a useful <code>ToString()</code>, but what about more complex objects? As has often been the answer lately, we can use higher-order functions:</p>
<pre>    public static T Dbg&lt;T, R&gt;(this T value, Func&lt;T, R&gt; selector)
    {
        Debug.WriteLine(selector(value));
        return value;
    }

    public static T Dbg&lt;T, R&gt;(this T value, string category, Func&lt;T, R&gt; selector)
    {
        Debug.WriteLine(selector(value), category);
        return value;
    }</pre>
<p>Now we can provide a delegate to trace whatever we want without affecting the object itself. For example, we can easily trace a row count for the <code>DataView</code> being returned:</p>
<pre>public DataView GetResults()
{
    var myTable = GetDataTable();
    // Process data...
    return myTable.DefaultView.Dbg("Result Count", v =&gt; v.Count);
}</pre>
<p>I could go on, but you get the idea.</p>
<h3>PowerShell Filter</h3>
<p>Finally, we can implement similar functionality in PowerShell using a filter with an optional scriptblock parameter:</p>
<pre>filter Debug([scriptblock] $sb = { $_ })
{
  [Diagnostics.Debug]::WriteLine((&amp; $sb))
  $_
}

PS &gt; 1..3 | Debug { $_*2 } | %{ $_*$_ }
1
4
9</pre>
<p>Which traces 2, 4, 6, as expected.</p>
<p><strong>Update 4/19/2009:</strong> Changed functions to use category overloads. And another point to consider: if the value being traced could be <code>null</code>, <code>selector</code> should be designed accordingly to avoid <code>NullReferenceException</code>. There&#8217;s nothing worse than bugs introduced by tracing or logging.</p>
<br /> Tagged: Debugging, higher-order function <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/solutionizing.wordpress.com/500/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/solutionizing.wordpress.com/500/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/solutionizing.wordpress.com/500/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=solutionizing.net&#038;blog=3982353&#038;post=500&#038;subd=solutionizing&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://solutionizing.net/2009/04/14/elegant-inline-debug-tracing/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/26483382e3717e58e4c45d06c8ec351d?s=96&#38;d=identicon&#38;r=PG" medium="image">
			<media:title type="html">dahlbyk</media:title>
		</media:content>
	</item>
	</channel>
</rss>
