Apply DeMorgan’s law refactoring

October 23, 2009

After reading up on some refactorings after a few hours of refactoring today, I thought it might be nice to share this refactoring with everyone.

I ran into some code today, a simple equality comparison method, except it was comparing about 7 properties, so even worse than this:

public bool Compare(item x, item y)
{
return !(x.a != y.a || x.b != y.b || x.c != y.c);
}

Even though it doesn’t take long to figure out what it is doing, it takes more time to figure out than if we applied DeMorgan’s law in what is known as avoiding double negatives refactoring:


public bool Compare(item x, item y)
{
return x.a == y.a && x.b == y.b && x.c == y.c;
}

Any time you run across code where you negate a set of conditions, do everyone else a favor and invert the conditions.  Apply DeMorgan’s law to make the code more readable. To freshen up on the rules, visit http://en.wikipedia.org/wiki/De_Morgan’s_laws.  Saving even 30 seconds of translation every time someone looks at that line of code, becomes a huge savings.


OrderBy().Descending()

October 5, 2009

Just wanted to share a quick extension method, it’s really simple yes but it’s power is in reducing lines of code.   If you have ever wanted to apply an order by clause to a collection of items and conditionally do this based on a direction, you know that the only choices available are different methods OrderBy and OrderByDescending.  It really is too bad because the internal OrderedEnumerable has a boolean flag for direction that would have been nice as a parameter, but better yet why not make it fluent while we are at it!

Normally we might have to write code like this, assuming I want to order by a particular key in a dictionary field on the item record. (This is just a sample of a nasty selector for ordering that we wouldn’t want to be copy & pasting):


if(ascending)
{
items = items.OrderBy(i => i.DictionaryField.Keys.Contains(key) ? i.DictionaryField[key] : null)
}
else
{
items = items.OrderByDescending(i => i.DictionaryField.Keys.Contains(key) ? i.DictionaryField[key] : null)
}

The next refactoring might be, which might not be so bad if we could use var instead of Func…, but c# doesn’t deal well with implicit functions because of the static typing thing!

Func<Item, object> nastySelector = i => i.DictionaryField.Keys.Contains(key) ? i.DictionaryField[key] : null;
if(ascending)
{
items = items.OrderBy(nastySelector);
}
else
{
items = items.OrderByDescending(nastySelector);
}

Next, I can combine the if/else using the ternary operator:

Func<Item, object> nastySelector = i => i.DictionaryField.Keys.Contains(key) ? i.DictionaryField[key] : null;
items = ascending ? items.OrderBy(nastySelector) : items.OrderByDescending(nastySelector);

This is pretty good, but it’s not very readable. A chained Descending method (on OrderBy results) would be nice, ridding us of the Func declaration garble and even making our items assignment much more fluent!

ordered = items.OrderBy(i => i.DictionaryField.Keys.Contains(key) ? i.DictionaryField[key] : null);
items = ascending ? ordered : ordered.Descending();

So here is the Descending implementation, this is for Enumerable lists only, if you have an IQueryable collection, cast it to IEnumerable first. This makes use of reflection to set the internal field (descending) on the internal class that you are eternally not supposed to touch :) .

public static IOrderedEnumerable<TSource> Descending<TSource>(this IOrderedEnumerable<TSource> source)
{
var field = source.GetType().GetField("descending", BindingFlags.NonPublic | BindingFlags.Instance);
if(field == null)
{
throw new ArgumentException("Source must be OrderedEnumerable");
}

field.SetValue(source, true);

return source;
}


ForEach or ForEachCopyIntoNewList?

October 2, 2009

All of us have desired a ForEach extension method in .Net for a while now, after being spoiled with all the new syntactic sugar with lambdas and linq in c#.  We’ve no doubt all implemented our own, here is the one I use:

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action)
{
foreach (var item in source)
{
action(item);
}
}

My only issue with this and the foreach loop itself, is that you cannot modify the original collection with your action.  There are plenty of cases where we only have a Remove method on a collection and would like to have a RemoveAll.  To get around this issue, we can copy items into a new list and iterate over it.  With this we can even remove items from the original collection!  However, I am now wondering if this should be the default behavior of a ForEach extension method:

public static void ForEachCopyIntoNewList<T>(this IEnumerable<T> source, Action<T> action)
{
var items = source.ToList();
items.ForEach(action);
}

I am wondering what everyone thinks, obviously this has implications for delayed execution / lazy loaded scenarios but with that aside, thoughts?  I am also looking for a good name to keep this as an alternative extension method but ForEachCopyIntoNewList is rather icky, so if you have a suggestion please let me know.


The slippery slope of “var”

September 24, 2009

The var keyword has been a rather controversial addition to the C# language.  Many developers initially fear it, getting lost in demos that use it.  Eventually, they come to understand it as something “lazy” programmers would use and often dismiss it.  I’ve gone through these stages.  I even remember my blood boiling when I saw resharper, out of the box, suggest to use it!  I never really understood it as anything more than implicit typing.

Recently, I decided that I should learn new concepts with new languages instead of just trying to learn and do examples in the same old.  Why not kill two birds with one stone!  I’ve been exploring a lot of interpreted languages (functional and imperative), focusing on Scheme (LISP) and python.  I’ve had a great joy reading and conceptualizing new things in these language.

Studying new concepts and applying them with dynamic languages has made me notice, more than ever, all the boiler plate type code to get anything done in C#.  After a weekend of hacking in python, I find myself skipping type declarations in C# only to get compiler errors :( .  The simplicity of names = ('Bob', 'John') in python is doubled in C# to List<string> names = new List<string>{ "Bob", "John" }; without any added value!

I have been struggling to find ways to bring this simplicity to C#, short of switching to python altogether :) .  My favorite way is to cut some of the crap and go with var names = new List<string>{ "Bob", "John" };.  No loss of information and some added clarity!  However, the use of var is often frowned upon as if it were unprofessional, my peers reading my latest code only to comment on my “abuse” of it!

What I was missing is the next step in the progression of understanding var. I was starting to realize that it adds clarity through readability!  No longer do I have to scan through a bunch of type verbiage in a variable declaration to find the name, let alone the content.  Readability alone wasn’t convincing my critics so I pondered on the topic some more in regards to another set of concepts I have been working to grasp, DDD.

In studying DDD (Domain Driven Design) I detected a sense of deja vu.  The core concepts, of creating a ubiquitous language and model that permeates code, was resonating all the way down to the level of variables.  If a variable represents a list of employee names, it should be labeled employeeNames. If we cram that much intent and meaning into our variable names, why do we even care what primitive or compound type is used?

employeeNames might be implemented as a List<string> in C# or a simple list in python.  However, when all is said and done, employeeNames is neither a List<string> in C# nor a list in python.  Thinking about it as such adds no value, just translation overhead.  employeeNames is simply a variable to store employee names, it’s type is employeeNames!  The name implies this directly.  It describes a kind of name, employee, and it’s plural, clearly a collection or set of names.  The same would apply for a variable to represent age, even if implemented as an integer, it’s not an integer, it is an age!

I think this is the answer to help convince people that using var is actually a good thing.  Especially when writing unit tests where readability is a primary concern.  I would even go so far as to suggest using it anywhere when declaring a variable.  The only argument I have heard against this, thus far, is that this will lead to ambiguity.  But wait a minute, I think the opposite is true!  Static typing leaves room for intention to be left in the type itself.  Because of this, developers get sloppy with variable names.  When developers don’t have a type to prefix a variable, they typically put more intention into the name, for their own sanity!

I would be more inclined to believe I would run across List<string> employees = new List<string>(); in C# than employees = ('Bob', 'John')in python.  This example requires knowledge that employees is implemented as a list of strings for someone to extrapolate that employees holds names and not ages or something else.  However, with a list of strings, this may just be a guess!  It could be a list of their emails or maybe home addresses!  I know I’ve seen this in the past and I know I’ve done it myself.  This added translation only decreases the maintainability of the code.

So the next evolution, in the slope of understanding and using var will be understanding it as a tool of readability and to help avoid leaving intention in types.  This adds a layer of linguistic abstraction that hides the implementation of our variable’s type and makes it more flexible.

I think the last evolution with var, will be to help developers get more familiar with the ideas behind dynamic typing.  Implicit typing is like a step in the direction of dynamic typing.  The last thing to do, seems to be to drop the use of var at all.  It’s simply linguistic boilerplate to developers (even if it serves a purpose to the C# evaluator).

So get your var on, don’t be ashamed!


My cool code snippet

August 22, 2009

I submitted this to the Resharper cool code snippet competition and thought I would share it with everyone else, including why it’s cool!

[Test]
public void $METHOD$_$SCENARIO$_$EXPECTATION$()
{
$END$
}

I’ve been doing a lot of TDD lately and I am constantly writing new tests. So my number one snippet is one that creates a simple test. I’ve tweaked this template a lot, it started out with a simple test template with only one editable occurance for a name. In “The Art of Unit Testing,” Roy Osherove talks about test readability which starts with the test name itself. He suggests putting the test method name together with three components. First, name the method under test (the Act in AAA), that way related tests for the same method are easy to identify (and actually R# sorts test fixture test methods by name so this is even more useful with Code Cleanup :) ). Second, name it with a scenario, what is unique about the given context of the test (known as the Arrange in AAA). Finally, include the outcome of the test, the expectation (Assert in AAA). This way you know all of what will go into the test before you write it!

I gave his naming scheme a try and found out it offers a pit of success. If you cannot name these three parts then your test likely won’t be readable. Anyone should know what a test does without reading it, like with any method, it should be intention revealing! Without identifying a scenario explicitly, it may be blurred in several lines of setup (Arrange). Having the scenario in the name makes it explicit and makes me keep it simple (I hate long method names). The test may have too many expectations, again, I hate long method names so if I find myself putting multiple expectations in the name I will quickly realize I need to move the other expectations to new tests (SRP with testing)!

The same day I tried using this test method naming convention, was the same day I created this test snippet and have kept it ever since. Every time I write a test, I am very explicit and careful, which is very important with TDD, not to take on too much with any one test!

This snippet is awesome, not because of the code it creates, but because it sets myself up for success every time I use it, like having Uncle Bob Martin watching over my shoulder :)


Outlook 2010 + Google Cal Sync hack

August 6, 2009

So yeah Google Cal Sync doesn’t work with Outlook 2010 Preview, but I found a way to get it to jive.

I edited Outlook.exe in C:\Program Files\Microsoft Office\Office14 using Notepad++ with the Hex-Editor plugin. At assembly location 0x000c09b2, I changed the value to 0×32, in the ascii dump. It originally read (14.0.0 and now reads (12.0.0

Good luck, I have no idea what this might break, I hope it is just the outlook version that the add in manager reports to add ins :) . I have successfully synced events to and from my GCal!

-Wes


If you are doing custom Linq to Sql mappings, it currently doesn’t support having your own base Entity class that you extend all your entities from. I found out the hard way through painful debugging. However, it seems if you do this with the version of .net 3.5 sp1 on the Win 7 RC it will work, so this may not be a bug forever!

August 4, 2009

If you are doing custom Linq to Sql mappings, it currently doesn’t support having your own base Entity class that you extend all your entities from. I found out the hard way through painful debugging. However, it seems if you do this with the version of .net 3.5 sp1 on the Win 7 RC it will work, so this may not be a bug forever!


NUnit 2.5.1 framework with Silverlight 3

July 31, 2009

We’re doing some Silverlight development at work and I’m doing some off to the side. I like to stick with a familiar, proven unit test framework. NUnit 2.5.1. has some great new attributes to use during testing (actually these came out in 2.5) such as Timeout and MaxTime. To take advantage of them you have to have a version of NUnit compiled as a silverlight library or at least recompiled referencing the core of silverlight (system.dll and mscorlib versions 2.0.5.0).

In the spirit of continuing what a few other people have done, I have compiled the latest version of the NUnit framework into a SL library and want to make it available. The work of the following guys has helped me use NUnit up to version 2.4 and helped me get 2.5.1 going as well!

A nice template that included the SL framework version, if someone wants this updated please let me know and I can do that too, otherwise I’ll just post my dlls:
http://weblogs.asp.net/nunitaddin/archive/2008/05/01/silverlight-nunit-projects.aspx

A set of instructions to port the framework to SL (I diverged on some of these, see below):
http://www.jeff.wilcox.name/2009/01/nunit-and-silverlight/

Here is the list of changes and what didn’t make the cut:

  • BinarySerializableConstraint – SL core doesn’t have BinarySerializer
  • AssertionException, IgnoreException, InconclusiveException, SuccessException – cannot be serialized, SL core doesn’t have SerializationAttribute (goes along with BinarySerializer)
  • RequiresSTA and RequiresMTA attributes

How was this pulled off?

  • For both the nunit.framework and nunit.framework.tests I added new silverlight libraries and copied the links to the code that the respective projects already referenced. I also added a nunit.silverlight to drop in some of the following additional classes that are needed but not in the SL core.
  • I want to thank Jeff Wilcox for his original work on some shims
    • ArrayList which I added a ToArray method that takes a type, of course this was ripped off of the ArrayList (via reflector) in the .Net core so someone should let me know if MSFT is going to come take away my computer for publishing this
    • Hashtable
  • I added a ListDictionary which is just a version of the generic Dictionary class with key and value set to type object
  • String.Compare(string,string,bool) – a version of string comparison not included in the silverlight core, again thank you reflector
  • I made up an ApplicationException as this wasn’t in the SL core
  • I made a version of the non generic Comparer class that isn’t in the SL core, thanks reflector
  • I added the compiler directive NET_2_0
  • A lot of the functionality that was removed was done so by leveraging the SILVERLIGHT compiler directive to exclude the relevant code.

I also went into the framework tests and tweaked a new solution to work with silverlight. I had to modify the tests as follows:

  • CanTestContentsOfSortedList excluded – no SortedList in SL
  • Remove references and tests with System.Data types (NotGreaterEqualIComparable, NotGreaterIComparable, NotLessEqualIComparable, NotLessIComparable)
  • Remove SameColorAs constraint, which was only referenced by NamedAndUnnamedColorsCompareAsEqual, which was commented out anyways
  • Remove BinarySerializableTest and XmlSerializableTest tests that depend on Serializable attribute
  • Changed DifferentEncodingsOfSameStringAreNotEqual test to use System.Text.Encoding.UTF8.GetString(byte[],start,length) overload as (byte[]) overload isn’t available in SL
  • Removed CodeShouldNotCompile and CodeShouldNotCompileAsFinishedConstraint as Microsoft.CSharp.CSharpCodeProvider is not available in SL

So, altogether the changes were minimal and there are 1273 tests passing on the SL version of the framework!

To use these assemblies:

  1. Setup a SL library as your test library.
  2. Download the SL libraries here
  3. Include a reference to the nunit.framework.dll.
  4. If you have trouble getting tests to run (missing file exceptions to SL assemblies) then set “Copy Local: true” on the appropriate assembly reference in the properties. I always have to do this for the system SL assembly.

If anyone wants more source for what I did or more bits of the nunit framework (like mocks or w/e) ported, please let me know and I will get that done, if possible :) For now I’m happy with just the framework as I use Rhino.Mocks (which already has a SL port) as an isolation container.

-Wes


Not using a ubiquitous language when developing an application is incurring yet another form of design debt, the overhead involved in manual testing is similar to the overhead incurred in translating between separate languages when conversations between users/domain experts and developers occur. Like with foreign languages, idiomatic assumptions and other misunderstandings are likely to fall short of a true conversation, so just pony up and focus on using a COMMON LANGUAGE as Eric Evans refers to in DDD.

July 26, 2009

Not using a ubiquitous language when developing an application is incurring yet another form of design debt, the overhead involved in manual testing is similar to the overhead incurred in translating between separate languages when conversations between users/domain experts and developers occur. Like with foreign languages, idiomatic assumptions and other misunderstandings are likely to fall short of a true conversation, so just pony up and focus on using a COMMON LANGUAGE as Eric Evans refers to in DDD.
Me


Null Object Pattern

July 21, 2009

Code reuse is very important for developers, most of the patterns and refactorings exist soley to reduce the smell of duplicated code. Null checks are one of the biggest culprits of duplicated code. It is also, to a degree, a concern that often gets scattered through out an application and isn’t properly separated. Without testing and/or good documentation, it’s often hard to determine the expectations of a method that returns a reference type or a nullable value type. Often, unnecessary, paranoid, null checks are incorporated to deal with the problem.

The null object pattern almost solely exists as a pattern to reduce code, so if it cannot reduce the amount of code you are writing, don’t use it!

The idea is that instead of setting a refernece type to null initially, you set it to an implementation of the type that executes “null behavior” if methods are called on it’s contract that would normally throw a null reference exception.

Pros

  • Redcue code
  • Separated concerns when handling null logic

Cons

  • Not familiar to newer developers
  • Can complicate code, make sure it is actually reducing the amount of code before implementing! This is not a pattern to start with in a standard toolset!

Say we have a contract for a type:

	public interface IThing
	{
		void Do();
		bool Execute();
	}

and your system made a large number of calls to this Do method but had to check if the Thing was null before calling Do/Execute, you could replace the initial value of a reference to it with a Null implementation instead, then if someone calls a method on a null instance it won’t have any side effects (including null reference exceptions) if it wasn’t initialized already.

	public class NullThing : IThing
	{
		public void Do()
		{

		}

		public bool Execute()
		{
			return true;
		}
	}

Then, anywhere that used this type could initilize to the NullThing:

	public class ThingHaver
	{
		private IThing _Thing = new NullThing();
		public IThing Thing
		{
			get
			{
				return _Thing;

			}
			set
			{
				_Thing = value;
			}
		}
	}

What would be really cool is if we could somehow overload the default operator in c# and set what it returns. Then, if we used an abstract base class of IThing (ThingBase), we could implement this to return our NullThing(), assuming that behind the scenes the compiler relied on wiring up calls to default whenever it ran across:

private ThingBase _Thing;

Then we wouldn’t even have to set our variable to NullThing! Though maybe I’m getting too far off on a tangent here :) My one concern with this pattern is that it is very easy to produce a disparity in a team if they all aren’t aware of the pattern or it’s implementation in a particular scenario.

-Wes


Follow

Get every new post delivered to your Inbox.