<?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>Musings&#60;Biefeld&#62; &#187; Coding</title>
	<atom:link href="http://sbiefeld.com/category/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://sbiefeld.com</link>
	<description>- curiosities of development, life, the universe and everything -</description>
	<lastBuildDate>Tue, 02 Feb 2010 04:32:48 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Step by Step to Using MSpec (Machine.Specifications) with ReSharper</title>
		<link>http://sbiefeld.com/2009/08/27/step-by-step-to-using-mspec-machine-specifications-with-resharper/</link>
		<comments>http://sbiefeld.com/2009/08/27/step-by-step-to-using-mspec-machine-specifications-with-resharper/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 20:33:52 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[BDD]]></category>
		<category><![CDATA[Behavior Driven Design]]></category>
		<category><![CDATA[Git]]></category>
		<category><![CDATA[MSpec]]></category>
		<category><![CDATA[ReSharper]]></category>
		<category><![CDATA[Specifications]]></category>
		<category><![CDATA[Unit Test]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=391</guid>
		<description><![CDATA[
Whilst researching using MSpec with ReSharper I found it difficult to find all the resources I needed in one place. This is an attempt to condense everything into that one place and facilitate those seeking to accomplish the same task.
Step 1 &#8211; Git It:
First thing&#8217;s first, grab the latest Machine Spec source from github.
$ git [...]]]></description>
			<content:encoded><![CDATA[<p><br/>
<p>Whilst researching using MSpec with ReSharper I found it difficult to find all the resources I needed in one place. This is an attempt to condense everything into that one place and facilitate those seeking to accomplish the same task.</p>
<h3>Step 1 &#8211; Git It:</h3>
<p>First thing&#8217;s first, grab the latest Machine Spec source from github.</p>
<pre style="background-color: #141414;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #BEBEC8; font-size: 10pt;">$ git clone git://github.com/machine.machine.specifications.git mspec</pre>
<h3>Step 2 &#8211; Build It:</h3>
<p>Next, open it up in Visual Studio, set it to build in release mode and build it. Now the binaries will be ready for you.
</p>
<h3>Step 3 &#8211; Setup ReSharper:</h3>
<p>Now we need to setup ReSharper to be able to utilize the MSpec framework and run the tests in ReSharper&#8217;s test runner. To do this we need to add a plugins directory to the &#8220;JetBrains\ReSharper\v4.5\Bin&#8221; directory or the where ever the bin directory for your ReSharper is located. In the Plugins create a Machine.Specifications directory, so you should now have a path similar to; &#8220;JetBrains\ReSharper\v4.5\Bin\Plugins\Machine.Specifications&#8221;. Place the following dlls in the newly created folder: Machine.Specifications.ReSharperRunner.4.5.dll and Machine.Specifications.dll.
</p>
<h3>Step 4 &#8211; Write some Specifications:</h3>
<p>Coolio, now to test some behaviors, the dlls needed in our test project; Machine.Specifications.dll, Machine.Specifications.NUnit.dll or Machine.Specifications.XUnit.dll, and the appropriate test framework dll.</p>
<p><br/>
<p>Let&#8217;s take a look at a couple of examples to get used to the syntax. The most common keywords you want to pay attention to are <strong>Subject, Establish, Because</strong> and <strong>It</strong>. Declare the Subject of your Spec, Establish a context of the spec, Because x occurs, It should do something. For more complex scenarios you can use the keyword, <strong>Behaves_like</strong> and the <strong>Behaviors</strong> attribute which allows you to define complex behaviors. If you need to perform some cleanup use the <strong>Cleanup</strong> keyword.</p>
<p>Now for a couple of simple contrived examples&#8230;</p>
<p>This first specification looks at adding two numbers:</p>
<pre style="background-color: #141414;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #BEBEC8; font-size: 10pt;">[<span style="color: #7386a5;">Subject</span>(<span style="color: #8f9d6a;">"adding two operands"</span>)]
<span style="color: #cda869;">public class</span> <span style="color: #7386a5;">when_adding_two_operands</span>
{
	<span style="color: #cda869;">static decimal</span> value;

	<span style="color: #7386a5;">Establish</span> context <span style="color: #cda869;">=</span> () <span style="color: #cda869;">=&gt;</span>
		value <span style="color: #cda869;">=</span> <span style="color: #9B7032;">0m</span>;

	<span style="color: #7386a5;">Because</span> of <span style="color: #cda869;">=</span> () <span style="color: #cda869;">=&gt;</span>
		value <span style="color: #cda869;">= new</span> Operator().Add(<span style="color: #9B7032;">42.0m</span>, <span style="color: #9B7032;">42.0m</span>);

	<span style="color: #7386a5;">It</span> should_add_both_operands <span style="color: #cda869;">=</span> () <span style="color: #cda869;">=&gt;</span>
		value.ShouldEqual(<span style="color: #9B7032;">84.0m</span>);
}</pre>
<p>The second specification looks at adding multiple numbers:</p>
<pre style="background-color: #141414;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #BEBEC8; font-size: 10pt;">[<span style="color: #7386a5;">Subject</span>(<span style="color: #8f9d6a;">"adding multiple operands"</span>)]
<span style="color: #cda869;">public class</span> <span style="color: #7386a5;">when_adding_multiple_operands</span>
{
	<span style="color: #cda869;">static decimal</span> value;

	<span style="color: #7386a5;">Establish</span> context <span style="color: #cda869;">=</span> () <span style="color: #cda869;">=&gt;</span>
		value <span style="color: #cda869;">=</span> <span style="color: #9B7032;">0m</span>;

	<span style="color: #7386a5;">Because</span> of <span style="color: #cda869;">=</span> () <span style="color: #cda869;">=&gt;</span>
		value <span style="color: #cda869;">= new</span> Operator().Add(<span style="color: #9B7032;">42m</span>, <span style="color: #9B7032;">42m</span>, <span style="color: #9B7032;">42m</span>);

	<span style="color: #7386a5;">It</span> should_add_all_operands <span style="color: #cda869;">=</span> () <span style="color: #cda869;">=&gt;</span>
		value.ShouldEqual(<span style="color: #9B7032;">126m</span>);
}</pre>
<p>The code being tested:</p>
<pre style="background-color: #141414;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #BEBEC8; font-size: 10pt;"><span style="color: #cda869;">public class</span> <span style="color: #7386a5;">Operator</span>
{
	<span style="color: #cda869;">public decimal</span> Add(<span style="color: #cda869;">decimal</span> firstOperand, <span style="color: #cda869;">decimal</span> secondOperand)
	{
		<span style="color: #cda869;">return</span> firstOperand <span style="color: #cda869;">+</span> secondOperand;
	}

	<span style="color: #cda869;">public decimal</span> Add(<span style="color: #cda869;">params decimal</span>[] operands)
	{
		<span style="color: #cda869;">decimal</span> value <span style="color: #cda869;">=</span> <span style="color: #9B7032;">0m</span>;

		<span style="color: #cda869;">foreach</span> (<span style="color: #cda869;">var</span> operand <span style="color: #cda869;">in</span> operands)
		{
			value <span style="color: #cda869;">+=</span> operand;
		}

		<span style="color: #cda869;">return</span> value;
	}
}</pre>
<h3>Step 5 &#8211; Create Templates to Improve Your Efficiency:</h3>
<p>
Using ReSharper templates is a good way to improve your spec writing efficiency, the following are templates I have been using.</p>
<p>This first one is for your normal behaviors:</p>
<pre style="background-color: #141414;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #BEBEC8; font-size: 10pt;">[Subject("$subject$")]
public class when_<span style="color: #cda869;">$when$</span>
{
	Establish context =()=&gt;	{};

	Because of =()=&gt; {};		

	It should_$should$ =()=&gt; <span style="color: #7386a5;">$END$</span>;
}</pre>
<p>This one&#8217;s for assertions by themselves:</p>
<pre style="background-color: #141414;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #BEBEC8; font-size: 10pt;">It should_<span style="color: #cda869;">$should$</span> =()=&gt; <span style="color: #7386a5;">$END$</span>;</pre>
<h3>Step 6 &#8211; Run the Report</h3>
<p>The report generated is pretty much the exact same as the SpecUnit report. The easiest thing to do is place the following MSpec binaries and file in the directory where your test binaries are placed; CommandLine.dll, Machine.Specifications.ConsoleRunner.exe, Machine.Specifications.dll and CommandLine.xml. The command to run the report goes a little something like:</p>
<pre style="background-color: #141414;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #BEBEC8; font-size: 10pt;">machine.specifications.consolerunner --html &lt;the location you want the html report stored&gt; &lt;your test dll name&gt;</pre>
<p>This is the report generated from the example specs:<br/><br/><img src="http://sbiefeld.com/wp-content/uploads/2009/08/MSpecReportExample.PNG" alt="MSpecReportExample" title="MSpecReportExample" width="434" height="390" class="alignnone size-full wp-image-394" style="border: solid 1px #ddd;" /></p>
<p><br/>
<p>Well, that&#8217;s about all for now, let me know if you have any questions.</p>
<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2009/08/27/step-by-step-to-using-mspec-machine-specifications-with-resharper/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Testing with a Compiled Class that Doesn&#8217;t Implement an Interface &#8211; Adapter Pattern</title>
		<link>http://sbiefeld.com/2009/05/12/testing-with-a-compiled-class-that-doesnt-implement-an-interface-adapter-pattern/</link>
		<comments>http://sbiefeld.com/2009/05/12/testing-with-a-compiled-class-that-doesnt-implement-an-interface-adapter-pattern/#comments</comments>
		<pubDate>Wed, 13 May 2009 04:32:12 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design Patterns]]></category>
		<category><![CDATA[Adapter Pattern]]></category>
		<category><![CDATA[Compiled Class]]></category>
		<category><![CDATA[Implement Interface]]></category>
		<category><![CDATA[Specification]]></category>
		<category><![CDATA[Unit Test]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=288</guid>
		<description><![CDATA[
*UPDATE: Per&#160;sean chambers, this is an example of the&#160;adapter pattern

I recently ran into an issue where I needed to implement a simple email service to send users a randomly generated PIN when they are first entered into the system. To accomplish this I decided to just use the System.Net.Mail implementation.&#160; To create and send an [...]]]></description>
			<content:encoded><![CDATA[<p><br/>
<p>*UPDATE: Per&nbsp;<a href="/members/schambers/default.aspx" target="_blank">sean chambers</a>, this is an example of the&nbsp;<a href="http://en.wikipedia.org/wiki/Adapter_pattern" target="_blank">adapter pattern</a></p>
<p><br/></p>
<p>I recently ran into an issue where I needed to implement a simple email service to send users a randomly generated PIN when they are first entered into the system. To accomplish this I decided to just use the <a target="_blank" title="system.net.mail" href="http://msdn.microsoft.com/en-us/library/system.net.mail.aspx">System.Net.Mail</a> implementation.&nbsp; To create and send an email you have to use the <a target="_blank" title="SmtpClient" href="http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx">SmtpClient</a> class which does not implement an interface. All I really wanted to test was that the Send() method was called, I did not want to write an integration test that actually sends an email.</p>
<p><br/></p>
<p>One way to work around this problem is to create an interface containing the elements you need to mock from the compiled class.&nbsp; After this, create your own class that inherits the compiled class and implements your interface. Now when testing, you can seemingly mock up the non-interfaced compiled class, which is exactly what I wanted to achieve. I am not sure whether this is the appropriate way to handle the issue, if anyone has any thoughts on a better way to do this, I would be grateful for the advice.</p>
<p>My specification ended up looking like this:</p>
<p><br/></p>
<pre style="background-color: #141414;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #BEBEC8; font-size: 10pt;"><span style="color: #cda869;">public class</span> <span style="color: #7386a5;">EmailServiceSpecs</span> : <span style="color: #7386a5;">ContextSpecification</span>
{
	<span style="color: #cda869;">protected</span> <span style="color: #d0da90;">IEmailService</span> _emailService;
	<span style="color: #cda869;">protected</span> <span style="color: #d0da90;">ISmtpClient</span> _smtpClient;
	<span style="color: #cda869;">protected string</span> _emailTo <span style="color: #cda869;">=</span> <span style="color: #8f9d6a;">"phillip.fry@planetexpress.com"</span>;
	<span style="color: #cda869;">protected string</span> _emailFrom <span style="color: #cda869;">=</span> <span style="color: #8f9d6a;">"hermes.conrad@planetexpress.com"</span>;
	<span style="color: #cda869;">protected string</span> _emailSubject <span style="color: #cda869;">=</span> <span style="color: #8f9d6a;">"New Process to Improve Morale"</span>;
	<span style="color: #cda869;">protected string</span> _emailBody <span style="color: #cda869;">=</span> <span style="color: #8f9d6a;">"From now on all employees will be required to have Brain slugs, remember, a mindless worker is a happy worker."</span>;

	<span style="color: #cda869;">protected override void</span> SharedContext()
	{
		<span style="color: #7386a5;">DependencyInjection</span><span style="color: #cda869;">.</span><span style="color: #7386a5;">RegisterType</span>&lt;<span style="color: #d0da90;">IEmailService</span>, <span style="color: #7386a5;">EmailService</span>&gt;();

		_emailService <span style="color: #cda869;">=</span> <span style="color: #7386a5;">DependencyInjection</span>
			<span style="color: #cda869;">.</span>GetDependency&lt;<span style="color: #d0da90;">IEmailService</span>&gt;(_emailTo, _emailFrom, _emailSubject, _emailBody);

		_smtpClient <span style="color: #cda869;">=</span> <span style="color: #7386a5;">MockRepository</span>.GenerateMock&lt;<span style="color: #d0da90;">ISmtpClient</span>&gt;();

		<span style="color: #7386a5;">DependencyInjection</span><span style="color: #cda869;">.</span>RegisterInstance(_smtpClient);
	}
}

[<span style="color: #7386a5;">TestFixture</span>]
[<span style="color: #7386a5;">Concern</span>(<span style="color: #8f9d6a;">"Email Service"</span>)]
<span style="color: #cda869;">public class</span> <span style="color: #7386a5;">when_sending_an_email</span> : <span style="color: #7386a5;">EmailServiceSpecs</span>
{
	<span style="color: #cda869;">protected override void</span> Context()
	{
		_smtpClient.Stub(smptClient <span style="color: #cda869;">=&gt;</span> smptClient<span style="color: #cda869;">.</span>Send(<span style="color: #cda869;">new</span> <span style="color: #7386a5;">MailMessage</span>()))
			<span style="color: #cda869;">.</span>IgnoreArguments()
			<span style="color: #cda869;">.</span>Repeat<span style="color: #cda869;">.</span>Any();

		_emailService<span style="color: #cda869;">.</span>Send();
	}

	[<span style="color: #7386a5;">Test</span>]
	[<span style="color: #7386a5;">Observation</span>]
	<span style="color: #cda869;">public void</span> should_send_email()
	{
		_smtpClient<span style="color: #cda869;">.</span>AssertWasCalled<
			(smtpClient <span style="color: #cda869;">=&gt;</span> smtpClient<span style="color: #cda869;">.</span>Send(<span style="color: #cda869;">new</span> MailMessage()),
			assertionOptions <span style="color: #cda869;">=&gt;</span> assertionOptions<span style="color: #cda869;">.</span>IgnoreArguments());
	}
}
</pre>
<p>Below are my email classes:</p>
<pre style="background-color: #141414;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #BEBEC8; font-size: 10pt;"><span style="color: #cda869;">public interface</span> <span style="color: #d0da90;">ISmtpClient</span>
{
	<span style="color: #cda869;">void</span> Send(<span style="color: #7386a5;">MailMessage</span> message);
}

[<span style="color: #7386a5;">MapDependency</span>(<span style="color: #cda869;">typeof</span>(<span style="color: #d0da90;">ISmtpClient</span>))]
<span style="color: #cda869;">public class </span><span style="color: #7386a5;">SubsideSmtpClient</span> : <span style="color: #7386a5;">SmtpClient</span>, <span style="color: #d0da90;">ISmtpClient</span> { }

<span style="color: #cda869;">public interface</span> <span style="color: #d0da90;">IEmailService</span>
{
	<span style="color: #cda869;">void</span> Send();
}

[<span style="color: #7386a5;">MapDependency</span>(<span style="color: #cda869;">typeof</span>(<span style="color: #d0da90;">IEmailService</span>))]
<span style="color: #cda869;">public class</span> <span style="color: #7386a5;">EmailService</span> : <span style="color: #d0da90;">IEmailService</span>
{
	<span style="color: #cda869;">public</span> <span style="color: #7386a5;">EmailService</span>(<span style="color: #cda869;">string</span> to, <span style="color: #cda869;">string</span> from, <span style="color: #cda869;">string</span> subject, <span style="color: #cda869;">string</span> body)
	{
		Email = <span style="color: #cda869;">new</span> <span style="color: #7386a5;">MailMessage</span>(from, to, subject, body);
	}

	<span style="color: #cda869;">protected</span> <span style="color: #7386a5;">MailMessage</span> Email
	{
		<span style="color: #cda869;">get</span>; <span style="color: #cda869;">set</span>;
	}

	<span style="color: #cda869;">private</span> <span style="color: #d0da90;">ISmtpClient</span> _smptClient;

	<span style="color: #cda869;">protected</span> <span style="color: #d0da90;">ISmtpClient</span> Smtp
	{
		<span style="color: #cda869;">get</span>
		{
			_smptClient = <span style="color: #7386a5;">DependencyUtilities</span>
				<span style="color: #cda869;">.</span>RetrieveDependency(_smptClient);
			<span style="color: #cda869;">return</span> _smptClient;
		}
	}

	<span style="color: #cda869;">public void</span> Send()
	{
		Smtp<span style="color: #cda869;">.</span>Send(Email);
	}
}
</pre>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2009/05/12/testing-with-a-compiled-class-that-doesnt-implement-an-interface-adapter-pattern/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>My Visual Studio Twilight theme</title>
		<link>http://sbiefeld.com/2009/04/14/my-visual-studio-twilight-theme/</link>
		<comments>http://sbiefeld.com/2009/04/14/my-visual-studio-twilight-theme/#comments</comments>
		<pubDate>Wed, 15 Apr 2009 05:54:05 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[ASPX]]></category>
		<category><![CDATA[Color Scheme]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[XML]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=208</guid>
		<description><![CDATA[
I just finalized my text color theme for visual studio. Just thought I would share it with everyone. It is geared towards those of you who have resharper installed, but it should still work fine without it.

The theme is based off of the textmate twilight theme. I was going for a low contrast theme that [...]]]></description>
			<content:encoded><![CDATA[<p><br/>
<p>I just finalized my text color theme for visual studio. Just thought I would share it with everyone. It is geared towards those of you who have resharper installed, but it should still work fine without it.</p>
<p><br/></p>
<p>The theme is based off of the <a href="http://wiki.macromates.com/Themes/UserSubmittedThemes" target="_blank">textmate</a> twilight theme. I was going for a low contrast theme that is easy on the eyes.&nbsp; I have tried the Vibrant Ink theme and it is too abrasive for me. My goal was to make warnings and errors blatantly obvious and distinguish classes from interfaces. I also love how the comments are dark and do not draw attention, I am not a big fan of comments.&nbsp; I think the code along with BDD tests should be self-explanatory of what is going on.</p>
<p><br/></p>
<p>All resharper warnings show up as red text. Build errors have red squiggly lines under them.&nbsp; Breakpoints have red background. </p>
<p><br/></p>
<p>Here is a c# example:</p>
<p><br/></p>
<p><img src="http://www.lostechies.com/cfs-filesystemfile.ashx/__key/CommunityServer.Components.UserFiles/00.00.00.21.37/TwilightCs.PNG" /></p>
<p><br/></p>
<p>Here is an example of an aspx page:</p>
<p><br/></p>
<p><img src="http://www.lostechies.com/cfs-filesystemfile.ashx/__key/CommunityServer.Components.UserFiles/00.00.00.21.37/TwilightAspx.PNG" /></p>
<p><br/></p>
<p>Style sheet example:</p>
<p><br/></p>
<p><img src="http://www.lostechies.com/cfs-filesystemfile.ashx/__key/CommunityServer.Components.UserFiles/00.00.00.21.37/TwilightCss.PNG" /></p>
<p><br/></p>
<p>JavaScript example:</p>
<p><br/></p>
<p><img src="http://www.lostechies.com/cfs-filesystemfile.ashx/__key/CommunityServer.Components.UserFiles/00.00.00.21.37/TwilightJs.PNG" /></p>
<p><br/></p>
<p>Let me know if you have any suggestions.</p>
<p><br/></p>
<p><a target="_blank" href="http://www.lostechies.com/cfs-file.ashx/__key/CommunityServer.Components.UserFiles/00.00.00.21.37/MyTwighlightTheme.zip">Grab the Visual Studio settings file here!</a></p>
<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2009/04/14/my-visual-studio-twilight-theme/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Developing at the Speed of Microsoft</title>
		<link>http://sbiefeld.com/2009/03/03/developing-at-the-speed-of-microsoft/</link>
		<comments>http://sbiefeld.com/2009/03/03/developing-at-the-speed-of-microsoft/#comments</comments>
		<pubDate>Wed, 04 Mar 2009 01:13:39 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Rant]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=194</guid>
		<description><![CDATA[
As .net developers do you ever feel like Microsoft is hindering your development by the development tools they impose on us. I have been thinking about this lately and decide to discuss it, or this might actually be a rant, forgive the rant. I aim to take a brief look at web development the Microsoft [...]]]></description>
			<content:encoded><![CDATA[<p><br/></p>
<p>As .net developers do you ever feel like <a target="_blank" href="http://en.wikipedia.org/wiki/Microsoft">Microsoft i</a>s hindering your development by the development tools they impose on us. I have been thinking about this lately and decide to discuss it, or this might actually be a rant, forgive the rant. I aim to take a brief look at web development the Microsoft way, how it has evolved, and the hindrances imposed on the community.</p>
<h3>The Microsoft Web Development World</h3>
<p>Now I have never developed Microsoft web applications pre-webforms, i.e. pre-<a target="_blank" href="http://en.wikipedia.org/wiki/ASP.NET">Asp.net</a>, so I am not going to comment on that. What I am going to focus on is Microsoft&#8217;s asp.net development frameworks. As a side note, I have not done much development on the windows side of things, but it seems that it has been stagnating. I would love to see Microsoft write some bindings for <a target="_blank" href="http://en.wikipedia.org/wiki/GTK%2B">GTK+</a> and/or <a target="_blank" href="http://en.wikipedia.org/wiki/Qt_(toolkit)">Qt</a>, and support those cross platform toolkits. Pie in the sky dreams, I know.</p>
<h4>ASP.NET &#8211; Web Forms</h4>
<p>Somehow in their brilliance, big brother decided that abstracting HTML and Javascript into a infinitely more complex framework would be a good idea. This is ludicrous, don&#8217;t introduce unnecessary bloat into a framework. The page life cycle is ridiculous, all the built in webform controls use some retarded infinite inheritance scheme. Also what&#8217;s Microsoft&#8217;s infatuation with span tags, they wrapped all their webform controls in them.</p>
<p><br/></p>
<p> Lol, I know this is common knowledge and has been discussed at length before but I still have to deal with it on a daily basis and it feels like I&#8217;m trying to cut off my leg with a steak knife. My interest lies in finding the true reasoning behind this. I have to working theories. One is that Microsoft is so loving and kind towards their developers that they wanted to coddle them, and that coddling most likely stemmed from their lack of respect for us and our intelligence.  The other theory is that Microsoft convoluted the framework without realizing it due to their arrogance, believing they own the world and the way they are doing things must be right.</p>
<h4>ASP.NET AJAX</h4>
<p>Next the <a target="_blank" href="http://en.wikipedia.org/wiki/Web_2.0">web 2.0</a> boom arrived and everyone was clamoring for more interactive web UIs. The .net developers yelled loud enough and long enough that they wanted to have the same thing that they were witnessing in other web frameworks. The keyword here is <a target="_blank" href="http://en.wikipedia.org/wiki/ASP.NET_AJAX">ajax</a>. So what does Microsoft do, they don&#8217;t take this moment and think about totally redesigning their asp.net framework, they say lets create some more complex web controls and use them in conjunction with an uber-complex ajax framework. </p>
<p><br/></p>
<p>Awesome, we now how fresh steamy poo piled on top of old rotting, festering poo. Thanks big brother. Instead of realizing their mistakes they made with web forms they exacerbate the problem. Now we get a seemingly dumbed down ajax scheme, oh just wrap everything in an update panel and Microsoft will do the rest. Besides the fact that this removes all control you have over the interactions between the server and client, you also can not use any other javascript inside of these panels. So once again it boils down to arrogance, contempt, and a lack of foresight.</p>
<h4>ASP.NET MVC</h4>
<p>Now, Microsoft sees a significant proportion of developers moving to <a target="_blank" href="http://en.wikipedia.org/wiki/Ruby_(programming_language)">ruby</a> utilizing the <a target="_blank" href="http://en.wikipedia.org/wiki/Ruby_on_Rails">ruby on rails framework</a>. Also the community is yelling and screaming again, must be appeasement time. Did Microsoft actually take an introspective look and realize how ass backwards webforms is? Doubtful, they just figured out that they better do something to try and hold onto market share and give the community some fools gold. So they copy ruby on rails, ooooh, way to go big brother, you&#8217;re so innovative!</p>
<p><br/></p>
<p> It is way too late in the game, <a target="_blank" href="http://en.wikipedia.org/wiki/ASP.NET_MVC_Framework">asp.net mvc</a> is something Microsoft should have done long ago. Back when they were formulating asp.net webforms. There is no excuse for Microsoft not to have created a framework like this when they introduced the asp.net ajax stuff. It&#8217;s ridiculous, and still they are losing market share, I wonder why. </p>
<p><br/></p>
<p>They ignore their base long enough and they won&#8217;t have a base. What are we supposed to drink the kool-aid and be satisfied, the <a target="_blank" href="http://en.wikipedia.org/wiki/Model-view-controller">MVC pattern</a> is how old? Oh, wow they are supporting a way to <a target="_blank" href="http://en.wikipedia.org/wiki/Unit_testing">unit test</a> the UI interactions, wow how progressive you are Microsoft. Where is the support for plugins, where is the support for <a target="_blank" href="http://en.wikipedia.org/wiki/Representational_State_Transfer">RESTful web services</a>? The point is there is nothing to be impressed about, it&#8217;s ridiculous that people are excited, this should have happened long ago.</p>
<h3>Conclusion</h3>
<p>Now don&#8217;t get your panties in a wad I&#8217;m not all cynical, I like <a target="_blank" href="http://en.wikipedia.org/wiki/C_Sharp_(programming_language)">c#</a> as a language, even thought it is a static language and I like the <a target="_blank" href="http://en.wikipedia.org/wiki/Common_Language_Runtime">CLR</a>. Hopefully MVC is a sign that Microsoft is going to be moving at a less stagnant pace. I don&#8217;t think they will be. </p>
<p><br/></p>
<p>Things like <a target="_blank" href="http://www.mono-project.com/Main_Page">Mono</a>, <a target="_blank" href="/controlpanel/blogs/posteditor.aspx/http:/www.nhibernate.org/ ">NHibernate</a>, the <a target="_blank" href="http://altdotnet.org/">alt.net community</a> supplement the failings of the giant, but we should be fed up. Microsoft doesn&#8217;t listen, because of their corporate culture, which i doubt will change. Adding things to the web framework that should have been there long ago is nothing to celebrate, there i said it, <a target="_blank" href="http://www.youtube.com/watch?v=_6rAUUoaNZo">&#8220;Big whoop, want to fight about it&#8221;</a>. </p>
<p><br/></p>
<p>On a larger scale, why is Microsoft not listening to the community more, why are they not seeking to improve the community along the lines of the ruby community?  Where is Microsoft&#8217;s version of package management like <a target="_blank" href="http://en.wikipedia.org/wiki/RubyGems">ruby gems</a>? Where&#8217;s their continuous integration/build tool? Where&#8217;s their testing framework? Where&#8217;s there promotion of best software practices, i.e. <a target="_blank" href="/blogs/chad_myers/archive/2008/03/07/pablo-s-topic-of-the-month-march-solid-principles.aspx">SOLID</a>, <a target="_blank" href="http://en.wikipedia.org/wiki/Test-driven_development">TDD</a>, <a target="_blank" href="http://en.wikipedia.org/wiki/Behavior_Driven_Development">BDD</a>, <a target="_blank" href="http://en.wikipedia.org/wiki/Agile_software_development">Agile methodologies</a>, <a target="_blank" href="http://blog.scottbellware.com/2009/02/decade-of-agile-dawn-of-lean.html">Lean methodologies</a>? The answer is no where, all of that exists inside the community without Microsoft&#8217;s support. </p>
<p><br/></p>
<p>The community is bettering ourselves in spite of Microsoft&#8217;s stagnation. Now think what could be accomplished if they actually fully embraced the community and threw their money and clout behind what the community stands for, it would be great. I am very doubtful that will happen, though, I think it will take mass exodus from .net development for Microsoft to ever get the message. If nothing happens the .net community will continue to stagger along at the pace of Microsoft, it will not reach its potential, and the community will wither and die. </p>
<p><br/></p>
<p>There is an entire software industry that needs to mature, the .net community is but a sub-section of it.&nbsp; It would be great if we could lead the industry in best practices and passion for our craft.</p>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2009/03/03/developing-at-the-speed-of-microsoft/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Presenter Logic &#124;&#124; Domain Service Logic &#124;&#124; Repository Logic?</title>
		<link>http://sbiefeld.com/2009/02/18/presenter-logic-domain-service-logic-repository-logic/</link>
		<comments>http://sbiefeld.com/2009/02/18/presenter-logic-domain-service-logic-repository-logic/#comments</comments>
		<pubDate>Thu, 19 Feb 2009 05:22:33 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[Domain Service]]></category>
		<category><![CDATA[Presenter]]></category>
		<category><![CDATA[View]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=186</guid>
		<description><![CDATA[
Obviously the answer to the titular question is yes.

I have recently found myself questioning whether the logic I am coding belongs in a domain service or in the presenter. I actually found the same logic in the presenter residing the base repository. Something definitely smells wrong, almost like the putrid smell of death, lol, nah [...]]]></description>
			<content:encoded><![CDATA[<p><br/>
<p>Obviously the answer to the titular question is yes.</p>
<p><br/></p>
<p>I have recently found myself questioning whether the logic I am coding belongs in a <a href="http://devlicio.us/blogs/casey/archive/2009/02/17/ddd-services.aspx" target="_blank">domain service</a> or in the presenter. I actually found the same logic in the presenter residing the base repository. Something definitely <a href="http://en.wikipedia.org/wiki/Code_smell" target="_blank">smells</a> wrong, almost like the putrid smell of death, lol, nah just a <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" target="_blank">DRY</a> smell and a hint of mixed responsibility odor. The presenter was calling the Repository directly which was kinda of an indicator, but it is valid to do so, depending on the scenario.</p>
<p><br/></p>
<p>The application that I am currently working in is a web application. That being said, I feel it is valid to consider the web limitations part of the current domain, not just a concern of the presentation. If we need to move to a windows app or something else, it will take a lot of refactoring, so why not just view the web&#8217;s issues as part of what affects the domain. Besides, is the purpose of the domain to be abstract enough to support multiple platforms or to dimish complexity? Anyway, that&#8217;s another discussion altogether, and I&#8217;m digressing.</p>
<p><br/></p>
<p>Here&#8217;s the skinny, that&#8217;s a valid colloquialism isn&#8217;t it. I found string to integer conversion happening in two different places. Once in the presenter, grabbing a string Id from the view, converting it, calling an overloaded GetById method from the repository or throwing an exception if the Id was invalid. The overloaded GetById method was in the base repository, it either accepted a string Id or integer Id, if the string Id was invalid it was throwing an exception. Yikes, this is scary, and to think I was the one that coded all this, frightening, I know. I am recovering so don&#8217;t you worry yourself. Now to the current code:</p>
<h3>Code to be Refactored:</h3>
<h4>Presenter</h4>
<pre style="background-color: #000;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #aaa; font-size: 10pt;">
<span style="color: #df8000;">public virtual void</span> InitializeView()
{
	<span style="color: #df8000;">if</span>(TreatmentIdIsValid())
		LoadTreatment();
	<span style="color: #df8000;">else</span>
		<span style="color: #df8000;">throw new</span> <span style="color: #2091af;">ApplicationException</span>(<span style="color: #df8000;">string</span>.Format(<span style="color: #800000;">"A Record of Waste cannot be completed because of the invalid treatment id: {0}"</span>, View.TreatmentId));
}

<span style="color: #df8000;">private bool</span> TreatmentIdIsValid()
{
	<span style="color: #df8000;">int</span> validTreatmentId; 

	<span style="color: #df8000;">bool</span> treatmentIdIsValid = <span style="color: #df8000;">int</span>.TryParse(View.TreatmentId, <span style="color: #df8000;">out</span> validTreatmentId); 

	<span style="color: #df8000;">if</span>(treatmentIdIsValid)
		CurrentTreatmentId = id; 

	<span style="color: #df8000;">return</span> treatmentIdIsValid;
} 

<span style="color: #df8000;">protected virtual void</span> LoadTreatment()
{
	<span style="color: #df8000;">try</span>
	{
		CurrentTreatment = <span style="color: #2091af;">Repository</span>&lt;<span style="color: #2091af;">ITreatmentRepository</span>&gt;.GetById(CurrentTreatmentId);
	}
	<span style="color: #df8000;">catch</span>
	{
		<span style="color: #df8000;">throw new</span> <span style="color: #2091af;">ApplicationException</span>(<span style="color: #800000;">"Could not retrieve the specified treatment"</span>);
	}
}
</pre>
<h4>Base Repository</h4>
<pre style="background-color: #000;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #aaa; font-size: 10pt;">
<span style="color: #df8000;">public virtual</span> Entity GetById(<span style="color: #df8000;">string</span> id)
{
	<span style="color: #df8000;">int</span> parsedId;

	<span style="color: #df8000;">if</span> (!<span style="color: #df8000;">int</span>.TryParse(id, <span style="color: #df8000;">out</span> parsedId))
		<span style="color: #df8000;">throw new</span> <span style="color: #2091af;">ApplicationException</span>(<span style="color: #800000;">"Could not convert the given id: "</span> + id + <span style="color: #800000;">" into an integer"</span>);

	<span style="color: #df8000;">return</span> GetById(parsedId);
}

<span style="color: #df8000;">public virtual</span> Entity GetById(<span style="color: #df8000;">int</span> id)
{
	<span style="color: #df8000;">return</span> Session.Get&lt;Entity&gt;(id);
}
</pre>
<p>I think that there is no place for logic in the repository it should be left to the domain service. You could even argue that this functionality is common and can be moved to a domain utility. For ease I am going to move it to a domain service. Now, lettuce see the refactoring to the code above:</p>
<h3>Refactored Code:</h3>
<h4>Presenter</h4>
<pre style="background-color: #000;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #aaa; font-size: 10pt;">
<span style="color: #df8000;">public virtual void</span> InitializeView()
{
	LoadTreatment();
}

<span style="color: #df8000;">protected virtual void</span> LoadTreatment()
{
	CurrentTreatment = <span style="color: #2091af;">RecordOfWasteService</span>.GetParentTreatmentById(CurrentTreatmentId);
}
</pre>
<h4>Domain Service</h4>
<pre style="background-color: #000;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #aaa; font-size: 10pt;">
<span style="color: #df8000;">public virtual</span> <span style="color: #2091af;">Treatment</span> GetParentTreatmentById(<span style="color: #df8000;">string</span> id)
{
	<span style="color: #df8000;">int</span> validTreatmentId;

	<span style="color: #df8000;">if</span> (!<span style="color: #df8000;">int</span>.TryParse(id, <span style="color: #df8000;">out</span> validTreatmentId))
		<span style="color: #df8000;">throw new</span> <span style="color: #2091af;">ApplicationException</span>(<span style="color: #800000;">"Could not convert the given treatment id: "</span> + id + <span style="color: #800000;">" into an integer"</span>);

	<span style="color: #df8000;">return</span> GetParentTreatmentById(validTreatmentId);
}

<span style="color: #df8000;">protected virtual </span><span style="color: #2091af;">Treatment</span> GetParentTreatmentById(<span style="color: #df8000;">int</span> treatmentId)
{
	<span style="color: #df8000;">try</span>
	{
		CurrentTreatment = <span style="color: #2091af;">Repository</span>&lt;<span style="color: #2091af;">ITreatmentRepository</span>&gt;.GetById(treatmentId);
	}
	<span style="color: #df8000;">catch</span>
	{
		<span style="color: #df8000;">throw new</span> <span style="color: #2091af;">ApplicationException</span>(<span style="color: #800000;">"Could not retrieve the specified treatment"</span>);
	}
}
</pre>
<h4>Base Repository</h4>
<pre style="background-color: #000;font-family: Lucida Console;padding: 5px;border:solid 1px #333; overflow: auto; color: #aaa; font-size: 10pt;">
<span style="color: #df8000;">public virtual</span> Entity GetById(<span style="color: #df8000;">int</span> id)
{
	<span style="color: #df8000;">return</span> Session.Get&lt;Entity&gt;(id);
}
</pre>
<p>Alrighty then, we got any logic out of the repository, I&#8217;m feeling better already, my face has gone from grimace to grin, and no not the McDonlad&#8217;s character Grimace. <a href="http://www.youtube.com/watch?v=xf69EEL3WBk" target="_blank">Super serial</a>, a la Al Gore about ManBearPig, what was <a href="http://sbiefeld.com/Stuff/grimace.jpg" target="_blank">Grimace</a>, was he what you turn in to if you only eat McDonalds and nothing else?</p>
<p><br/></p>
<p>The responsibility of the repository should be to read and write to persistence/web services/messages etc. The string validation logic is in the domain service, I may pull it out to a base service or utility service. Our presenter is so much simpler now, and not worried about logic that it shouldn&#8217;t have to worry about. Hmm, the cleanliness is delightful. There is no more duplication of logic in the presenter and repository, w00t! Now let me know your thoughts, comments, opinions etc. of dissent or agreement, it will help me and hopefully others learn and grow. I&#8217;m off to watch the some <a href="http://en.wikipedia.org/wiki/Teenage_Mutant_Ninja_Turtles_(1987_TV_series)" target="_blank">Teenage Mutant Ninja Turtle original series</a>, wow, I&#8217;m a nerd.</p>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2009/02/18/presenter-logic-domain-service-logic-repository-logic/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Entity Validation Ideation</title>
		<link>http://sbiefeld.com/2009/02/14/entity-validation-ideation/</link>
		<comments>http://sbiefeld.com/2009/02/14/entity-validation-ideation/#comments</comments>
		<pubDate>Sat, 14 Feb 2009 19:53:13 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[Entity]]></category>
		<category><![CDATA[Validation]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=145</guid>
		<description><![CDATA[Issue at Hand:
I have been recently sumo wrestling with the idea of entity validation in my mind. So far, the validation problem, which is like, E. Honda, has the advantage over my mind which is currently like, Chun Li. The worst thing is all the other thoughts in my head are constantly struggling against my [...]]]></description>
			<content:encoded><![CDATA[<h3>Issue at Hand:</h3>
<p>I have been recently <a href="http://en.wikipedia.org/wiki/Sumo" target="_blank">sumo wrestling</a> with the idea of entity validation in my mind. So far, the validation problem, which is like, <a href="http://sbiefeld.com/Stuff/EHonda.png" target="_blank">E. Honda</a>, has the advantage over my mind which is currently like, <a href="http://sbiefeld.com/Stuff/ChunLi.png" target="_blank">Chun Li</a>. The worst thing is all the other thoughts in my head are constantly struggling against my entity validation thoughts. As <a href="http://en.wikipedia.org/wiki/Homer_Simpson" target="_blank">Homer Simpson</a> says, &#8220;Every time I learn something new, it pushes some old stuff out of my brain&#8221;. Except for me E. Honda is doing his grab move, where he squeezes his opponent between his fat, and squeezing all of my current thoughts out of my brain. I don&#8217;t understand how sumo wrestling evolved as a sport, do they really have nothing to do in Japan. I bet it was the master creation of some drunken emperor. Umm, let&#8217;s see I want to watch two super fat dudes wearing nothing but a diaper try to knock each other out of circle with their bellies, muahahaha, they&#8217;ll be playing this sport for centuries!</p>
<h3>Ideation:</h3>
<p>I have been pondering about the idea of validation. <a href="http://www.dictionary.com" target="_blank">Dictionary.com</a> says valid is: <i>&#8220;sound; just; well-founded, producing the desired result; effective&#8221;</i>. <a href="http://en.wiktionary.org" target="_blank">Wiktionary&#8217;s</a> valid definition in terms of logic is:<i>&#8220;A formula or system that evaluates to true regardless of the input values.&#8221;</i> When we think of validation in a programmers state of mind, the definition of valid in the logical sense, seems to jive the best. If x == y then it is valid if x != y it is invalid.</p>
<p><br/></p>
<p>Entity validation is determined by business rules and processes. It appears that there are two fundamental approaches to validation, proactive and reactive validation.</p>
<h4>Reactive Validation:</h4>
<p>The most common way I have seen validation handled is the addition of an IsValid state to the entity.  A good way of implementing this approach can be found in a <a href="http://grabbagoft.blogspot.com/2007/10/entity-validation-with-visitors-and.html" target="_blank">posting by Jimmy Bogard</a>. Whenever a business rule or process is broken the entity is no longer in a valid state. Then the user is informed of the problem in a different layer of the application. This form of validation is a very reactive way of handling validation. Meaning that it waits until something bad happens and then performs a function to cope with the contaminated actions. I don&#8217;t like this reactionary response, I would rather use something more preventative.</p>
<h4>Proactive Validation:</h4>
<p>What is valid validation? I wonder how many times I can use the word valid, or one of its etymological children in this post? What is a valid number of uses? I think the answer is <a href="http://en.wikipedia.org/wiki/42_(number)" target="_blank">42</a>.</p>
<p><br/>
<p>So, is valid validation a proactive or reactive approach? I believe that proactive is always the best approach. My definition of proactive entity validation is never allowing an invalid entity to exist. This means removing the concept of an IsValid state on the entity. Once that is removed you don&#8217;t have to do an IsValid check everywhere in the application, which is my main gripe with the reactive solution. Is it valid for your domain to ever contain an entity in an invalid state, something about this scenario makes my skin crawl and stomach churn, or maybe it has to do with something I ate last night. Hmm, it was spicy so maybe. An invalid entity just seems like a bad idea, it is a treacherous force that will actively work against you like <a href="http://en.wikipedia.org/wiki/Saruman" target="_blank">Saruman&#8217;s</a> voice being cast across middle earth. I think being proactive is a much cleaner approach, and will cleanse your domain of IsValid checks. Wow, that is just a proof less rant.</p>
<p><br/></p>
<p>Now the question is, what&#8217;s the best way to implement such a proactive solution? That&#8217;s the <a href="http://sbiefeld.com/Stuff/EHonda.png" target="_blank">E. Honda</a> I have been wrestling with. Let&#8217;s go over the broad definition of proactive entity validation. An entity cannot be created if it does not meet the business rules. Once we have a valid entity it cannot be modified unless the modifications satisfy the business rules. The stumbling block arises when your entity&#8217;s validity is based on a certain context. For example, it is valid to have a physicians drug order without a signature. When the process requires that the order to be sent to the pharmacy, the order is only valid when it has a signature. Ah, now the proactive solution becomes tricky because valid is defined by context. Following the proactive approach I could not create the entity without a signature, because it would be an entity in an invalid state. The only solution that I have thought of to this is having a drug order without the signature and a drug order request that inherits drug order and has the signature. The pharmacy then receives that drug order request with the signature on it.</p>
<h3>Outro:</h3>
<p>I have not yet fully fleshed out the details of how exactly this would be implemented. I hope to hammer out a spike with a spiked drink. I do believe that using a proactive approach to entity validation falls more in line with domain driven design by having a tighter coupling to the business language. A drug order does not need a signature to exist. A drug order request with a signature fulfills the need of the drug order being sent to the pharmacy.</p>
<p><br/>
<p>Be a proactionary and not a reactionary.</p>
<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2009/02/14/entity-validation-ideation/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Identifying NHibernate Refactoring Points &#8211; Utilizing DRY</title>
		<link>http://sbiefeld.com/2009/02/11/identifying-nhibernate-refactoring-points-utilizing-dry/</link>
		<comments>http://sbiefeld.com/2009/02/11/identifying-nhibernate-refactoring-points-utilizing-dry/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 06:50:38 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[NHibernate]]></category>
		<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[.NET]]></category>
		<category><![CDATA[DRY]]></category>
		<category><![CDATA[Single Responsibility Principle]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=81</guid>
		<description><![CDATA[Today when preparing for our code review I happened upon a few methods in our base repository. Those methods were using NHibernate to retrieve collections of objects from persistence.  I started scanning over the methods and figuring out what they were trying to accomplish.  After understanding their function I noticed that they were [...]]]></description>
			<content:encoded><![CDATA[<p>Today when preparing for our code review I happened upon a few methods in our base repository. Those methods were using NHibernate to retrieve collections of objects from persistence.  I started scanning over the methods and figuring out what they were trying to accomplish.  After understanding their function I noticed that they were prime candidates for a refactoring.</p>
<p>The methods were:</p>
<pre><span class="keyword">public</span> <span class="keyword">virtual</span> <span class="class">IList</span>&lt;Entity&gt; GetAll()
{
	<span class="keyword">return</span> Session.CreateCriteria(<span class="keyword">typeof</span> (Entity)).List&lt;Entity&gt;();
}

<span class="keyword">public</span> <span class="keyword">virtual</span> <span class="class">IList</span>&lt;Entity&gt; GetActiveItems()
{
	<span class="class">ICriteria</span> criteria = Session
		.CreateCriteria(<span class="keyword">typeof</span>(Entity))
		.Add(<span class="class">Restrictions</span>.IsNull(<span class="string">"InactiveDate"</span>));

	<span class="keyword">return</span> criteria.List&lt;Entity&gt;();
}

<span class="keyword">public</span> <span class="keyword">virtual</span> <span class="class">IList</span>&lt;Entity&gt; GetItemsLikeName(<span class="keyword">string</span> name, <span class="keyword">string</span> columnToCompareBy)
{
	<span class="class">ICriteria</span> criteria = Session.CreateCriteria(<span class="keyword">typeof</span>(Entity))
		.Add(<span class="class">Restrictions</span>.IsNull(<span class="string">"InactiveDate"</span>))
		.Add(<span class="class">Restrictions</span>.Like(columnToCompareBy, name, <span class="class">MatchMode</span>.Start).IgnoreCase());

	<span class="keyword">return</span> criteria.List&lt;Entity&gt;();
}
</pre>
<h3>Analysis:</h3>
<p>Now the first thing that tipped me off to the need for Refactoring was the <a href="http://en.wikipedia.org/wiki/Don%27t_repeat_yourself" target="_blank">DRY</a> (Don&#8217;t pete and repete yourself) principle, which can be extrapolated into Attwood&#8217;s <a href="http://www.codinghorror.com/blog/archives/000805.html" target="_blank">Curly&#8217;s Law</a> and even further to the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle" target="_blank">Single Responsibility Principle</a>.  At least, I thinks DRY&#8217;s a principle, maybe it&#8217;s classified as a technique, or to be more in tune with coding hype a <a href="http://www.codinghorror.com/blog/archives/000589.html" target="_blank">code smell</a>. Lol, code smells, it may work if compared to flatulence but if you compare it to cheese, the more pungent the odor, the better the cheese.  Actually it has more to do with identifying different smells so that you know what needs to be refactored or reworked entirely. Anyway, they all pretty much are talking about the same thing, minimizing duplicate code/rules/processes.</p>
<h3>The Break Down:</h3>
<p>The first thing I noticed was the responsibility of all the methods, they are responsible for retrieving a collection of objects. I observed this by the methods&#8217; return types of <span class="class">IList</span>&lt;Entity&gt; and their names, <i>GetAll(), GetActiveItems(),GetItemsLikeName()</i>.</p>
<p>Next all of the methods are following the same basic pattern(process) of creating an <span class="class">ICriteria</span> object, setting the specified <span class="class">ICriterion</span>(where my object equals some value) on that ICriteria and finally executing the retrieval of the matching objects.  The following is some psuedo code of that pattern(process)</p>
<pre><span class="class">ICriteria</span> criteria = Session.CreateCriteria(<span class="keyword">typeof</span>(Entity))
		.Add(<span class="class">ICriterion</span>)
<span class="keyword">return</span> criteria.RetrieveMatchingObjects&lt;Entity&gt;;
</pre>
<h3>The Refactor:</h3>
<p>Now we know the reponsibility and the process of all three methods. From this knowledge we can refactor those methods to use one method, but we will want to keep the signatures of each method, because they still have a separate responsibility as well.  Let&#8217;s see the common concern is collection retrieval through different criteria. To address handling the different criteria we can utilize c#&#8217;s keyword <a href="http://msdn.microsoft.com/en-us/library/w5zay9db.aspx" target="_blank"><span class="keyword">params</span></a> to pass in a variable number of criterion. Now, our combined method signature should look like:</p>
<pre><span class="keyword">protected</span> <span class="keyword">virtual</span> <span class="class">IList</span>&lt;Entity&gt; GetAllItems(<span class="keyword">params</span> <span class="keyword">ICriterion</span>[] criterion)</pre>
<p>Our refactored method is ready to return a collection of objects and to accept n number of ICriterion.</p>
<p>Next we need to create our <span class="class">ICriteria</span> creation:</p>
<pre><span class="class">ICriteria</span> getCriteria = Session.CreateCriteria(<span class="keyword">typeof</span>(Entity));</pre>
<p>After that it&#8217;s on to handling our array of <span class="class">ICriterion</span>:</p>
<pre><span class="keyword">if</span> (criterion != <span class="keyword">null</span>)
{
	<span class="keyword">foreach</span> (<span class="keyword">var</span> criteria <span class="keyword">in</span> criterion)
	{
		getCriteria.Add(criteria);
	}
}
</pre>
<p>First we need to check if the array is null, it is always good to check for null before trying to loop through an <span class="class">IEnumrable</span>. Once we are sure that the array is not null we can loop through that bad boy and add the criterion to our <span class="class">ICriteria</span> object. At this point we can execute our query, I prefer burning at the stake, but it&#8217;s up to you. Anyway our retrieval and return will (survey says) look like:</p>
<pre><span class="class">IList</span>&lt;Entity&gt; result = getCriteria.List&lt;Entity&gt;();</pre>
<p>Next on the proverbial platter, both the <i>GetActiveItems()</i> and <i>GetItemsLikeName()</i> methods are using the same criteria in their queries, the null check of Inactive Date. Ah ha, another point to refactor, stop the repetition. Let&#8217;s create a read only<span class="class">ICriterion</span> property named <i>WhereInactiveDateIsNull</i>, remember <a href="http://www.hanselman.com/blog/TheWeeklySourceCode14FluentInterfaceEdition.aspx" target="_blank">fluent interfaces</a> are your friend. If the name is unclear now, it may make more sense in a bit, so chill.</p>
<pre><span class="keyword">protected</span> <span class="keyword">virtual</span> <span class="class">ICriterion</span> WhereInactiveDateIsNull
{
	<span class="keyword">get</span>
	{
		<span class="keyword">return</span> <span class="class">Restrictions</span>.IsNull(<span class="string">"InactiveDate"</span>);
	}
}</pre>
<p>Alright so we now have our one method to rule them all, or at least the three methods we were looking at before.</p>
<h3>The Result:</h3>
<p>So now all of our methods are going to call the method we created and tell that method their own specific responsibilites through the criterion they pass in.</p>
<pre><span class="keyword">protected</span> <span class="keyword">virtual</span> <span class="class">ICriterion</span> WhereInactiveDateIsNull
{
	<span class="keyword">get</span>
	{
		<span class="keyword">return</span> <span class="class">Restrictions</span>.IsNull(<span class="string">"InactiveDate"</span>);
	}
}

<span class="keyword">protected</span> <span class="keyword">virtual</span> <span class="class">IList</span>&lt;Entity&gt; GetAllItems(<span class="keyword">params</span> <span class="class">ICriterion</span>[] criterion)
{
	<span class="class">ICriteria</span> getCriteria = Session.CreateCriteria(<span class="keyword">typeof</span>(Entity));

	<span class="keyword">if</span> (criterion != <span class="keyword">null</span>)
	{
		<span class="keyword">foreach</span> (<span class="keyword">var</span> criteria <span class="keyword">in</span> criterion)
		{
			getCriteria.Add(criteria);
		}
	}

	<span class="keyword">return</span> getCriteria.List&lt;Entity&gt;();
}

<span class="keyword">public</span> <span class="keyword">virtual</span> <span class="class">IList</span>&lt;Entity&gt; GetAll()
{
	<span class="keyword">return</span> GetAllItems();
}

<span class="keyword">public</span> <span class="keyword">virtual</span> <span class="class">IList</span>&lt;Entity&gt; GetActiveItems()
{
	<span class="keyword">return</span> GetAllItems(WhereInactiveDateIsNull);
}

<span class="keyword">public</span> <span class="keyword">virtual</span> <span class="class">IList</span>&lt;Entity&gt; GetItemsLikeName(<span class="keyword">string</span> name, <span class="keyword">string</span> columnToCompareBy)
{
	<span class="class">ICriterion</span> whereColumnValueStartsWithNameIgnoringCase
		= <span class="class">Restrictions</span>.Like(columnToCompareBy, name, <span class="class">MatchMode</span>.Start).IgnoreCase();

       	<span class="keyword">return</span> GetAllItems
	(
		WhereInactiveDateIsNull,
		whereColumnValueStartsWithNameIgnoringCase
	);
}
</pre>
<h3>The Interlude:</h3>
<blockquote><p>&#8220;Oh, this little guy? I wouldn&#8217;t worry about this little guy.&#8221;</p></blockquote>
<p><br/>
<p>That just popped into my head, I must be astral projecting again. Seriously, if you don&#8217;t know what that quote is from, you fail at life, nah, just joking, <a href="http://en.wikiquote.org/wiki/Super_Troopers" target="_blank">look it up</a>. Hmm, it must be late, my mind is wandering. Blogging and jamming. Jamming, is that still a socially acceptable term? Jamming to <a href="http://en.wikipedia.org/wiki/The_Tangent" target="_blank">The Tangent</a>, great stuff.</p>
<h3>The Conclusion:</h3>
<p>Ah, the fruits of our labor are so sweet. Remember, I know it&#8217;s hard, but remmember when I was speaking of the fluent interface, ah now you remember. Excellent, so if we take a look at our new <i>GetItemsLikeName()</i> method we can see the fluency at work;</p>
<blockquote><p> we want to <i>GetAllItems(WhereInactiveDateIsNull,(and) whereColumnValueStartsWithNameIgnoringCase)</i>.</p></blockquote>
<p><br/>
<p> If you can&#8217;t glean what this is doing from the naming, I am sorry, but there is no hope for you, <img src='http://sbiefeld.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> . This fluent interface does several things, it decreases the learning curve for new-comers, increases the readability of our code, and overall increases the maintainability.</p>
<p>I find that the best thing to do is try to contemplate the Single Responsiblity Principle, Dont Repeat Yourself Principle, or other sundry names for it; when you are satisfying your broken tests, assuming you are testing first. I know that sometimes it can be hard but it is a fracking awesome practice to achieve. Even if you can&#8217;t see the common responsibilities at first, definitely try to find them after your tests pass. Red, Green, Refactor.</p>
<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2009/02/11/identifying-nhibernate-refactoring-points-utilizing-dry/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Pondering my understanding of Domain Driven Design</title>
		<link>http://sbiefeld.com/2009/02/09/pondering-my-understanding-of-domain-driven-design/</link>
		<comments>http://sbiefeld.com/2009/02/09/pondering-my-understanding-of-domain-driven-design/#comments</comments>
		<pubDate>Tue, 10 Feb 2009 05:33:51 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Domain Driven Design]]></category>
		<category><![CDATA[Twitter]]></category>
		<category><![CDATA[business]]></category>
		<category><![CDATA[context]]></category>
		<category><![CDATA[Software]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=68</guid>
		<description><![CDATA[
My pondering stems from a song (which hereby refers to a Twitter discussion, eh, why not?). This song was started by a tweet from one of my co-workers earlier today.

First a bit of background, I have been able to glean the key purpose(s) of Domain Driven Design from my co-workers and from researching it a [...]]]></description>
			<content:encoded><![CDATA[<p><br/>
<p>My pondering stems from a song (which hereby refers to a <a href="http://twitter.com" target="_blank">Twitter</a> discussion, eh, why not?). This song was started by a tweet from one of my co-workers earlier today.</p>
<p><br/></p>
<p>First a bit of background, I have been able to glean the key purpose(s) of <a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank">Domain Driven Design</a> from my co-workers and from researching it a bit here and there. Unfortunately, I have not been able to sit down and read through <a href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=pd_bbs_sr_1/190-7506535-4275666?ie=UTF8&amp;s=books&amp;qid=1234240861&amp;sr=8-1" target="_blank">Eric Evans&#8217; Domain Driven Design book</a>. So, you might say that I am some what of a novice when it comes to domain driven design. One might say my knowledge of it, is fairly infantile, but they would be mediocrates.</p>
<p><br/></p>
<p>I have learned are that <a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank">DDD</a> is a different mode of thinking about software. Analyzing the context of the business process you are reproducing with software and then translating that into the design said software.  You come up with things like the Ubiquitous Language to better serve the need to replicate the targeted processes. That being said a lot of it seems to be logical conclusions that one would arrive at through thought, trial and error over an amount of time.</p>
<p><br/></p>
<p>One of the key ideas that I took away from my gander into <a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank">DDD</a>, was that validation should happen at the domain level.  I have been wrestling with this idea in my mind for a week or two.  The wrestling began when I read a posting on <a href="http://codebetter.com/blogs/gregyoung/archive/2009/01/22/the-data-centric-universe.aspx" target="_blank">Anemic domain models</a> and subsequently read <a href="http://www.martinfowler.com/bliki/AnemicDomainModel.html" target="_blank">Martin Fowler&#8217;s original posting</a> on the subject.  After absorbing that information a light bulb ignited in my noggin, pretty much the whole domain model of the project I am currently working on satisfies the classic definition of an anemic domain model, i.e. classes containing only properties with getters and setters. Yikes! I realized that we had been doing everything wrong, all of our business logic was in our presenters. Well, there is no time to go back and correct everything at the moment. I have been striving to get away from this bad habit with our latest feature and it just so happens that today that along came a Twitter song regarding domain validation and more abstractly, anemic domain models.</p>
<p><br/></p>
<p>My co-worker had a wonderful question about defensive coding / unit testing and a statement regarding domain validation:</p>
<p><br/></p>
<blockquote><p><a href="http://twitter.com/derickbailey" target="_blank">@derickbailey</a>:<br />
&#8220;Q: should I do defensive unit testing / coding immediately, or wait until someone finds a bug to do the defensive coding?&#8221;<br />
&#8220;i&#8217;m sold on &#8220;model / view / presenter / presentation model&#8221; idea at this point. presentation model contains input validation&#8221;<br />
&#8220;example:&#8217;make sure i have a valid date time, not an empty string&#8217;. would you call that business rules? &#8220;</p></blockquote>
<p><br/></p>
<p>My overall response was yes, it is definitely worth defensive coding / unit testing, if you wait for the bug to crop up in the UI, it will be much more expensive to fix, which is expressed by <a href="http://blog.scottbellware.com/2009/02/design-flaws-hernias-and-anemic-quality.html" target="_blank">Scott Bellware&#8217;s latest posting</a>.  There were also some other various tweets about the difference between UI validation and validation in the domain. Validation as business constraints not processes.</p>
<p><br/></p>
<p>Derick&#8217;s question/statement led to this response from Bellware:</p>
<p><br/></p>
<blockquote><p><a href="http://twitter.com/bellware" target="_blank">@Bellware</a>:<br />
&#8220;why are business rules and input validation not the same?&#8221;
</p></blockquote>
<p><br/></p>
<p>Next, Bellware went into some abstract ideas that were relevant to the topic at hand, but went over my head completely.  It seems he enjoys doing this regularly <img src='http://sbiefeld.com/wp-includes/images/smilies/icon_biggrin.gif' alt=':D' class='wp-smiley' /> , but thats just my musings.  Anyway, he and Derick were discussing the abstractions, then Bellware stated some things to me about <a href="http://en.wikipedia.org/wiki/Domain-driven_design" target="_blank">DDD</a>:</p>
<p><br/></p>
<blockquote><p><a href="http://twitter.com/bellware" target="_blank">@Bellware</a>:<br />
&#8220;what if the only domain is the domain that creates the need for that validation?&#8221;<br />
&#8220;if it&#8217;s all you need to deal with, then you don&#8217;t need anything more elaborate&#8221;<br />
&#8220;a domain that isn&#8217;t built for a specific context is pure technical masturbation. it earns you demerit points, not promotions.&#8221;</p></blockquote>
<p><br/></p>
<p>Bellware&#8217;s statements got the Grey matter churning in my head. At first, I was thinking of domain and context synonymously in my head, but then he clarified it for me. Context refers to such things as a web application, an operating system application, hardware driver etc. Derick&#8217;s example of getting a date from a string can be viewed as strictly a concern when dealing with a web interface(context). Is Bellware proposing a domain should be geared towards a specific interface implementation? If a domain is not aimed at a specific context then is it a fruitless effort in self indulgence?</p>
<p><br/></p>
<p>Well, now I am stuck in an endless loop pondering my perceptions of DDD. It would probably be prudent to invest some time reading <a target="_blank" href="http://www.amazon.com/Domain-Driven-Design-Tackling-Complexity-Software/dp/0321125215/ref=pd_bbs_sr_1/190-7506535-4275666?ie=UTF8&amp;s=books&amp;qid=1234240861&amp;sr=8-1">Eric Evans&#8217; Domain Driven Design</a>, to get a better grasp on the tennents of DDD and the reasoning behind them.  I&#8217;m sure I will gain more understanding in time from research and mulling these ideas over in my head.</p>
<p><br/></p>
<p>As a side note, this song has proven to me the usefulness of a tool such as <a href="http://twitter.com" target="_blank">Twitter</a>.  I was somewhat skeptical of it at first, and had passed it off as another mundane social networking tool used to gratify the cravings of narcissists.  It seems it can be used for good and evil.</p>
<p><br/></p>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2009/02/09/pondering-my-understanding-of-domain-driven-design/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Making c# lambda expressions more readable</title>
		<link>http://sbiefeld.com/2009/02/06/making-c-lambda-expressions-more-readable/</link>
		<comments>http://sbiefeld.com/2009/02/06/making-c-lambda-expressions-more-readable/#comments</comments>
		<pubDate>Fri, 06 Feb 2009 23:44:02 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Lambda Expressions]]></category>
		<category><![CDATA[Unit Testing]]></category>
		<category><![CDATA[Rhino Mocks]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=17</guid>
		<description><![CDATA[How often do you use lambda expressions?  I use them a great deal, mostly when I am making method assertions in Rhino Mocks.  If you do the bare minimum, which i see a lot, the expression can be somewhat cryptic.

Less readable:
Users.Find(x =&#62; x.Id == selectedUserId)
I am guilty of doing this as well, without even realizing.  [...]]]></description>
			<content:encoded><![CDATA[<p>How often do you use lambda expressions?  I use them a great deal, mostly when I am making method assertions in <a href="http://ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a>.  If you do the bare minimum, which i see a lot, the expression can be somewhat cryptic.<br />
<br />
Less readable:</p>
<pre class="csharpcode">Users.Find(x =&gt; x.Id == selectedUserId)</pre>
<p>I am guilty of doing this as well, without even realizing.  Maybe I am just being nit picky.<br />
<br />
I think it is much more readable if you use something more descriptive than some arbitrary letter in the alphabet.<br />
<br />
More readable:<br />
</p>
<pre class="csharpcode">Users.Find(user =&gt; user.Id == selectedUserId)</pre>
<p>This becomes much more useful when you are coding more complex lambda expressions.  One example is when making a method assertion using <a href="http://ayende.com/projects/rhino-mocks.aspx">Rhino Mocks</a>.<br />
<br />
Less readable:</p>
<pre class="csharpcode">_userRepository.AssertWasCalled
(
     x =&gt; x.Save(newUser),
     o =&gt; o.IgnoreArguments()
);</pre>
<p>With that assertion we have two arbitrary letters, what the heck does ‘x’ and  ‘o’ represent.  Are we talking about hugs and kisses.  I don’t think so.<br />
<br />
So to remedy this, lets change ‘x’ to ‘userRepository’ and ‘o’ to ‘method assertion’.  I believe these terms will make the assertion much more readable and concise.<br />
<br />
More readable:</p>
<pre class="csharpcode">_userRepository.AssertWasCalled
(
     userRepository =&gt; userRepository.Save(newUser),
     methodAssertion =&gt; methodAssertion.IgnoreArguments()
);</pre>
<p>With that little change it is much easier to understand what is being asserted and what parameters are being set on that assertion.<br />
<br />
The hardest part is breaking the habit of using arbitrary letters.  In the long run a more descriptive expression improves the readability of the code.  It will also decrease the amount of time it takes a new person to understand the lambda expressions in the code base.</p>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2009/02/06/making-c-lambda-expressions-more-readable/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>JavaScript to Change CSS Class Based on Check Box State</title>
		<link>http://sbiefeld.com/2008/11/24/javascript-to-change-css-class-based-on-check-box-state/</link>
		<comments>http://sbiefeld.com/2008/11/24/javascript-to-change-css-class-based-on-check-box-state/#comments</comments>
		<pubDate>Mon, 24 Nov 2008 23:53:31 +0000</pubDate>
		<dc:creator>Sean Biefeld</dc:creator>
				<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[Check Box]]></category>
		<category><![CDATA[CSS]]></category>
		<category><![CDATA[HTML]]></category>

		<guid isPermaLink="false">http://sbiefeld.com/?p=16</guid>
		<description><![CDATA[ Here is some useful JavaScript that wrote today to change a CSS class based on the state of a checkbox.
function replaceCssClassOnElementBasedOnCheckBoxState(checkboxId, elementToChangeId, checkedCssClassName, uncheckedCssClassName)
{
    var selectedElement = document.getElementById(elementToChangeId);
    var checkBox = document.getElementById(checkboxId);
    if(selectedElement &#38;&#38; checkBox)
    {
       [...]]]></description>
			<content:encoded><![CDATA[<p><script src="http://sbiefeld.com/scripts/examples.js" type="text/javascript"></script> Here is some useful JavaScript that wrote today to change a CSS class based on the state of a checkbox.</p>
<pre><span class="keyword">function</span> replaceCssClassOnElementBasedOnCheckBoxState(checkboxId, elementToChangeId, checkedCssClassName, uncheckedCssClassName)
{
    <span class="keyword">var</span> selectedElement = document.getElementById(elementToChangeId);
    <span class="keyword">var</span> checkBox = document.getElementById(checkboxId);
    <span class="keyword">if</span>(selectedElement &amp;&amp; checkBox)
    {
        <span class="keyword">if</span>(checkBox.<span class="keyword">checked</span>)
            selectedElement.className = checkedCssClassName;
        <span class="keyword">else</span>
            selectedElement.className = uncheckedCssClassName;
    }
}</pre>
<p>For Example:</p>
<p class="uncheckedStyle" id="exDiv">
<input id="exCb" onclick="replaceCssClassOnElementBasedOnCheckBoxState('exCb', 'exDiv', 'checkedStyle', 'uncheckedStyle')" name="exCb" type="checkbox" /><label for="exCb">Check This!</label></p>
<p>The style of this div should change based on the state of the checkbox.</p>
]]></content:encoded>
			<wfw:commentRss>http://sbiefeld.com/2008/11/24/javascript-to-change-css-class-based-on-check-box-state/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
