<?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>Vidar's Musings &#187; code quality</title>
	<atom:link href="http://www.kongsli.net/nblog/tag/code-quality/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.kongsli.net/nblog</link>
	<description>Deep thoughts on shallow topics</description>
	<lastBuildDate>Fri, 27 Jan 2012 07:36:55 +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>ASP.NET 3.5: improving testability with System.Web.Abstractions</title>
		<link>http://www.kongsli.net/nblog/2009/05/03/aspnet-35-improving-testability-with-systemwebabstractions/</link>
		<comments>http://www.kongsli.net/nblog/2009/05/03/aspnet-35-improving-testability-with-systemwebabstractions/#comments</comments>
		<pubDate>Sun, 03 May 2009 09:37:01 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Agile]]></category>
		<category><![CDATA[asp.net]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[code quality]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[system.web.abstractions]]></category>
		<category><![CDATA[testability]]></category>
		<category><![CDATA[testing]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=127</guid>
		<description><![CDATA[The testability of ASP.NET code has long been a challenge; creating unit tests for your ASP.NET code has been difficult. One of the main points of the new ASP.NET MVC framework has been to make code written for it easily testable. However, not many people know that in ASP.NET 3.5, Microsoft has added a few [...]]]></description>
			<content:encoded><![CDATA[<p>The testability of ASP.NET code has long been a challenge; creating unit tests for your ASP.NET code has been difficult. One of the main points of the new ASP.NET MVC framework has been to make code written for it easily testable. However, not many people know that in ASP.NET 3.5, Microsoft has added a few features to make any ASP.NET applications, not only ASP.NET MVC applications, more easy to test. The System.Web.Abstractions assembly adds a few classes to the System.Web namespace that will help the situation. For instance, looking at the documentation for System.Web.HttpRequestBase, it states that</p>

<blockquote>The <span><span class="selflink">HttpRequestBase</span></span> class is an abstract class that contains the same members as the <span><a id="ctl00_mainContentContainer_ctl25" onclick="javascript:Track('ctl00_mainContentContainer_cpe37452_c|ctl00_mainContentContainer_ctl25',this);" href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.aspx">HttpRequest</a></span> class. The <span><span class="selflink">HttpRequestBase</span></span> class enables you to create derived classes that are like the <span><a id="ctl00_mainContentContainer_ctl26" onclick="javascript:Track('ctl00_mainContentContainer_cpe37452_c|ctl00_mainContentContainer_ctl26',this);" href="http://msdn.microsoft.com/en-us/library/system.web.httprequest.aspx">HttpRequest</a></span> class, but that you can customize and that work outside the ASP.NET pipeline. When you perform unit testing, you typically use a derived class to implement members that have customized behavior that fulfills the scenario that you are testing.</blockquote>

<p>Very well. Looking at the documentation for HttpRequest, we see that HttpRequest is not a decendent of HttpRequestBase as one might expect from the name. The reason for this is probably that that would break backwards compatability with older versions of ASP.NET. So, how can we exploit the HttpRequestBase then? The answer is the HttpRequestWrapper class which is a decendant of HttpRequestBase and has a constructor that takes an HttpRequest object as a parameter. Then, we can take the HttpRequest object passed to our code from the framework, wrap it inside an HttpRequestWrapper object and pass it on to our code as a HttpRequestBase object. As I will show you in the examples below, this will enable us to create unit tests of our code by creating fake implementations of ASP.NET framework clases (using Rhino.Mocks).</p>

<h4>Example #1: Testing a page codebehind file</h4>

<p>Take, for instance, this simple page codebehind code that we would like to test:
<pre class="c-sharp" name="code">using System;
using System.Web;</pre></p>

<p>public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
    }
}
The first step to take here, is to extract a method which take the request object as a parameter instead of fetching it from a method in a superclass. In general, this is a variation of the dependency injection pattern which in many situations will help us make our code testable (also, see <a href="http://www.kongsli.net/nblog/2008/09/19/pure-functions-and-testability/">my earlier related post</a>). Like so:
<pre class="c-sharp" name="code">using System.Web;
using System;</pre></p>

<p>public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        SetCacheablityOfResponse(Response);
    }</p>

<pre><code>public void SetCacheablityOfResponse(HttpResponse response)
{
    response.Cache.SetCacheability(HttpCacheability.NoCache);
}
</code></pre>

<p>}
So, then having extracted our code in a separate method, the next step is to change the parameter type of this method from HttpRequest to HttpRequestBase. Furthermore, when calling this method, we need to wrap the HttpRequest object by creating an instance of HttpRequestWrapper. The code, then, looks like this:
<pre class="c-sharp" name="code"">using System.Web;
using System;</pre></p>

<p>public partial class _Default : System.Web.UI.Page
{
    protected void Page_Init(object sender, EventArgs e)
    {
        SetCacheablityOfResponse(new HttpResponseWrapper(Response));
    }</p>

<pre><code>public void SetCacheablityOfResponse(HttpResponseBase response)
{
    response.Cache.SetCacheability(HttpCacheability.NoCache);
}
</code></pre>

<p>}
Having now prepared our code for testing, we can create a unit test where we test the SetCacheabilityOfResponse method:
<pre class="c-sharp" name="code">[TestMethod]
public void ShouldSetNoCacheabilityOnDefaultPage()
{
    _Default page = new _Default();
    MockRepository mocks = new MockRepository();
    HttpResponseBase responseStub = mocks.Stub&lt;HttpResponseBase&gt;();
    HttpCachePolicyBase cachePolicyMock = mocks.CreateMock&lt;HttpCachePolicyBase&gt;();
    With.Mocks(mocks).Expecting(delegate
    {
        SetupResult.For(responseStub.Cache).Return(cachePolicyMock);
        cachePolicyMock.SetCacheability(HttpCacheability.NoCache);
        LastCall.On(cachePolicyMock).Repeat.AtLeastOnce();
    }).Verify(delegate
    {
        page.SetCacheablityOfResponse(responseStub);
    });
}</pre>
If you are not familiar with Rhino.Mocks or any other mocking framework, there appears to be a lot going on in that test. The basic idea is that we create derivatives of the -Base classes and pass these to the code that we are going to test, mimicking the behavior of the &#8220;real&#8221; objects that the framework would pass our code at runtime. Also note that in this particular test we test the side effect of our code, namely that the code should call a the SetCacheability method with a specific parameter. This is achieved using a mock object.</p>

<h4>Example #2: Testing an HTTP Handler</h4>

<p>Given the following HTTP handler code:
<pre class="c-sharp" name="code">using System;
using System.Web;</pre></p>

<p>public class RedirectAuthenticatedUsersHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request.IsAuthenticated)
        {
            context.Server.TransferRequest("/farfaraway");
        }
    }
}
Again, we extract the code we want to test into a separate method, passing it a -Base object and wrap the object passed to us from the framework in a -Wrapper object:
<pre class="c-sharp" name="code">using System;
using System.Web;</pre></p>

<p>public class RedirectAuthenticatedUsersHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        TransferUserIfAuthenticated(new HttpContextWrapper(context));
    }</p>

<pre><code>public void TransferUserIfAuthenticated(HttpContextBase context)
{
    if (context.Request.IsAuthenticated)
    {
        context.Server.TransferRequest("/farfaraway");
    }
}
</code></pre>

<p>}
This allows us to create unit tests for the TransferUserIfAuthenticated method, for instance:
<pre class="c-sharp" name="code">[TestMethod]
public void ShouldRedirectAuthenticatedUser()
{
    RedirectAuthenticatedUsersHandler handler = new RedirectAuthenticatedUsersHandler();
    MockRepository mocks = new MockRepository();
    HttpContextBase httpContextStub = mocks.Stub&lt;HttpContextBase&gt;();
    HttpRequestBase httpRequestBaseStub = mocks.Stub&lt;HttpRequestBase&gt;();
    HttpServerUtilityBase httpServerUtilityMock = mocks.CreateMock&lt;HttpServerUtilityBase&gt;();
    With.Mocks(mocks).Expecting(delegate
    {
        SetupResult.For(httpContextStub.Request).Return(httpRequestBaseStub);
        SetupResult.For(httpContextStub.Server).Return(httpServerUtilityMock);
        SetupResult.For(httpRequestBaseStub.IsAuthenticated).Return(true);
        httpServerUtilityMock.TransferRequest("/farfaraway");
        LastCall.On(httpServerUtilityMock).Repeat.AtLeastOnce();
    }).Verify(delegate
    {
        handler.TransferUserIfAuthenticated(httpContextStub);
    });
}</pre></p>

<h4>Summary</h4>

<p>I have shown two very simple examples on how some of the classes in the System.Web.Abstractions assembly can help us test our ASP.NET code. I have used HttpResponseBase, HttpServerUtilityBase, HttpContextBase, HttpRequestBase, and HttpCachePolicyBase. Note that there are a number of classes available, so if you are faced with not being able to test your ASP.NET code because of dependencies to classes in the framework, take a look in the System.Web namespace and see if there are -Base classes that can help you out.</p>

<p>Testability is a large topic, and there is much to be said about it. I have shown a couple of very simple examples on how to improve testability. Testability has a lot to do with code design as well; in a real world I would write the test before writing the code and I would move my code out of codebehinds. Those topics are discussed a lot elsewere, hopefully this post will bring you a small step further in writing testable code.</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2009%2F05%2F03%2Faspnet-35-improving-testability-with-systemwebabstractions%2F&amp;title=ASP.NET%203.5%3A%20improving%20testability%20with%20System.Web.Abstractions" id="wpa2a_2"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2009/05/03/aspnet-35-improving-testability-with-systemwebabstractions/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Measurement of code quality</title>
		<link>http://www.kongsli.net/nblog/2008/09/25/measurement-of-code-quality/</link>
		<comments>http://www.kongsli.net/nblog/2008/09/25/measurement-of-code-quality/#comments</comments>
		<pubDate>Thu, 25 Sep 2008 10:48:09 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Software development]]></category>
		<category><![CDATA[code quality]]></category>
		<category><![CDATA[programming]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=69</guid>
		<description><![CDATA[No measurement beats WTFs/min!]]></description>
			<content:encoded><![CDATA[<p>No measurement beats <a href="http://www.osnews.com/story/19266/WTFs_m">WTFs/min</a>!</p>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2008%2F09%2F25%2Fmeasurement-of-code-quality%2F&amp;title=Measurement%20of%20code%20quality" id="wpa2a_4"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2008/09/25/measurement-of-code-quality/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pure functions and testability</title>
		<link>http://www.kongsli.net/nblog/2008/09/19/pure-functions-and-testability/</link>
		<comments>http://www.kongsli.net/nblog/2008/09/19/pure-functions-and-testability/#comments</comments>
		<pubDate>Fri, 19 Sep 2008 13:36:28 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Microsoft technologies]]></category>
		<category><![CDATA[Software development]]></category>
		<category><![CDATA[Software testing]]></category>
		<category><![CDATA[automated testing]]></category>
		<category><![CDATA[code quality]]></category>
		<category><![CDATA[programming]]></category>
		<category><![CDATA[unit test]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=68</guid>
		<description><![CDATA[When trying to introduce unit tests into an existing project, code dependencies is often a problem. During a teeth-grinding session grappling with this problem I came to think about pure functions. Pure functions are functions that (according to Wikipedia&#8216;s definition): always evaluates the same result value given the same argument value(s). The function result value [...]]]></description>
			<content:encoded><![CDATA[<p>When trying to introduce unit tests into an existing project, code dependencies is often a problem. During a teeth-grinding session grappling with this problem I came to think about pure functions.</p>

<p><a href="http://en.wikipedia.org/wiki/Pure_function">Pure functions</a> are functions that (according to <a href="http://en.wikipedia.org/wiki/Main_Page">Wikipedia</a>&#8216;s definition):</p>

<ul>
    <li>always evaluates the same result value given the same argument value(s). The function result value cannot depend on any hidden information or state that may change as program execution proceeds, nor can it depend on any external input from I/O devices, and</li>
    <li>evaluation of the result does not cause any semantically observable side effect or output, such as mutation of mutable objects or output to I/O devices.</li>
</ul>

<p>Seems to me that pure functions would be a wet dream for unit testing. Imagine, you could pass in whatever the function needed to execute, and then check its return value. No mocking about with mock objects with side effect expectations needed!</p>

<p>But alas, we live in a world with non-pure functions. Even in functional programming, which does explicitly keep any state, you find them. In an object oriented language a primary idea is that objects should carry state. An object has a state. Period. However, if we can be inspired by the notion of pure functions, and make methods that have less dependencies, we will be much better off when it comes to unit testing.</p>

<p>I my experience, the ASP.NET programming model with ASPX code behind files is a model that promotes writing methods that are problematic to create unit tests for.</p>

<p>Take, for example, the following (theoretical, I admit) code behind snippet example:
<pre style="padding-left: 30px;">protected void Page_Load(object sender, EventArgs e)</pre>
<pre>    {</pre>
<pre>        ShowOrHideEditButton(Page.User.Identity.Name);</pre>
<pre>    }</pre>
<pre>    void ShowOrHideEditButton(string currentUser)</pre>
<pre>    {</pre>
<pre>        if (Request.QueryString["user"].Equals(currentUser))</pre>
<pre>        {</pre>
<pre>            EditButton.Enabled = true;</pre>
<pre>        }</pre>
<pre>        else</pre>
<pre>        {</pre>
<pre>            EditButton.Enabled = false;</pre>
<pre>        }</pre>
<pre>    }</pre>
So, what is the problem here? Actually, there are two problems.</p>

<ol>
    <li>The ShowOrHideMethod is not only dependant on its input parameters, but also on another member variable. When looking at the method signature, you do not see this, and might be misleaded about what the outcome of the methods is dependent on.</li>
    <li>The method does not return any value, but has a side-effect on its environment (setting the edit button visibility).</li>
</ol>

<p>These two issues, makes it troublesome to test the method in a unit test. You have spend time to set up the methods context, and you have to measure the method&#8217;s side effects in order to make assesments about its result.</p>

<p>A much better approach would be something like this:
<pre>    protected void Page_Load(object sender, EventArgs e)</pre>
<pre>    {</pre>
<pre>        EditButton.Enabled = ShowOrHideEditButton(Page.User.Identity.Name, Request.QueryString["user"]);</pre>
<pre>    }</pre>
<pre>    bool ShowOrHideEditButton(string currentUserName, string profilePerson)</pre>
<pre>    {</pre>
<pre>        return (currentUserName.Equals(profilePerson));</pre>
<pre>    }</pre>
This way, we can easily test the ShowOrHideEditButton method in a unit test without having to use a great deal test code to set up the test context.</p>

<p>For increased testability, I would suggest the following for better method purity:</p>

<ul>
    <li>A method should evaluate the same result, given the same argument value(s) and object state.</li>
    <li>A method execution result should be represented as, in order of preference: 1) a return value, 2) changed object state (mutation), or 3) a side-effect on an I/O device</li>
</ul>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2008%2F09%2F19%2Fpure-functions-and-testability%2F&amp;title=Pure%20functions%20and%20testability" id="wpa2a_6"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2008/09/19/pure-functions-and-testability/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Breaking encapsulation with collections</title>
		<link>http://www.kongsli.net/nblog/2008/07/01/breaking-encapsulation-with-collections/</link>
		<comments>http://www.kongsli.net/nblog/2008/07/01/breaking-encapsulation-with-collections/#comments</comments>
		<pubDate>Tue, 01 Jul 2008 08:33:42 +0000</pubDate>
		<dc:creator>vidarkongsli</dc:creator>
				<category><![CDATA[Software development]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[code quality]]></category>
		<category><![CDATA[ienumerable]]></category>
		<category><![CDATA[immutable]]></category>
		<category><![CDATA[mutable]]></category>

		<guid isPermaLink="false">http://www.kongsli.net/nblog/?p=61</guid>
		<description><![CDATA[Encapsulation is one of the most important features of object orientation, but often easy to break in practice. One common mistake to make in this respect happens when creating a class that holds some sort of collection or array. For example, let&#8217;s assume that we want to make an immutable object (meaning that its state [...]]]></description>
			<content:encoded><![CDATA[<p>Encapsulation is one of the most important features of object orientation, but often easy to break in practice. One common mistake to make in this respect happens when creating a class that holds some sort of collection or array.</p>

<p>For example, let&#8217;s assume that we want to make an immutable object (meaning that its state should never change troughout its lifecycle):</p>

<blockquote><code>
public class Request
{
    private readonly string[] _acceptedTypes;
    public Request(params string [] acceptedTypes) {...}
    public string[] AcceptedTypes { get {...} }
    public bool Accepts(string type) {...}
}
</code>
</blockquote>

<p>We have a class that take a list of strings as parameter to the constructor. The intent is that the list of strings should never change. Typical use of the class would be something like this:</p>

<blockquote><code>
Request request = new Request("application/json", "application/x-json");
if (request.Accepts(somestring))
{
     ...
}
</code></blockquote>

<p>Here&#8217;s a naîve implementation of the class:</p>

<blockquote><code>
public class Request
{
    private readonly string[] _acceptedTypes;

    public Request(params string[] acceptedTypes)
    {
        _acceptedTypes = acceptedTypes;
    }

    public string[] AcceptedTypes { get { return _acceptedTypes; } }

    public bool Accepts(string type)
    {
        foreach (string acceptableType in _acceptedTypes)
        {
            if (acceptableType.Equals(type))
            {
                return true;
            }
        }
        return false;
    }
}
</code></blockquote>

<p>Our intent of creating an immutable object is here manifested in the &#8216;readonly&#8217; keyword used when defining the member variable _acceptedTypes, and the fact that there is only a set accessor for the AcceptedTypes property. But alas, there are several issues that break our intent.</p>

<p>First, let&#8217;s have a look at the AcceptedTypes accessor. It allows us to write code such as this:</p>

<blockquote><code>
request = new Request("application/json", "application/x-json" );

bool accepts1 = request2.Accepts("application/javascript");
request.AcceptedTypes[1] = "application/javascript";
bool accepts2 = request.Accepts("application/javascript");
</code></blockquote>

<p>After running this code, we find that accepts1 != accepts2. We have been able to manipulate the state of the object (in other words, it is mutable). The problem is that the AcceptedTypes exposes a reference to the array of types. Alternatively, it could only expose an IEnumerable that can be used to iterate over the types:</p>

<blockquote><code>
public IEnumerable<string> AcceptedTypes
{
    get
    {
        foreach (string acceptableType in _acceptedTypes)
        {
            yield return acceptableType;
        }
    }
}
</string></code></blockquote>

<p>Then, it will not be possible to manipulate the state of the object by calling request.AcceptedTypes[i].
Still, there is one problem with the current implementation. We still can write code such as this:</p>

<blockquote><code>
string[] types = new string[] { "application/json", "application/x-json" };
Request request = new Request(types);
bool accepts1 = request.Accepts("application/javascript");
types[1] = "application/javascript";
bool accepts2 = request.Accepts("application/javascript");
</code></blockquote>

<p>After running this code, accepts1 != accepts2. The problem is that we pass a referene to the constructor, and the object instance stores it in its local variable. We are free to change the object that our reference points to, indirectly changing the state of the object. In order to fix this, we change the constructor code for Request:</p>

<blockquote><code>
public Request(params string[] acceptedTypes)
{
    _acceptedTypes = new string[acceptedTypes.Length];
    Array.Copy(acceptedTypes, _acceptedTypes, acceptedTypes.Length);
}</code></blockquote>
<p><a class="a2a_dd a2a_target addtoany_share_save" href="http://www.addtoany.com/share_save#url=http%3A%2F%2Fwww.kongsli.net%2Fnblog%2F2008%2F07%2F01%2Fbreaking-encapsulation-with-collections%2F&amp;title=Breaking%20encapsulation%20with%20collections" id="wpa2a_8"><img src="http://www.kongsli.net/nblog/wp-content/plugins/add-to-any/share_save_120_16.png" width="120" height="16" alt="Share"/></a></p>]]></content:encoded>
			<wfw:commentRss>http://www.kongsli.net/nblog/2008/07/01/breaking-encapsulation-with-collections/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>

