DaedTech

Stories about Software

By

You Need CodeRush

Oops

The other day, I was chatting with some developers and one of them pulled me over to show me the following code:

private void SetLayout(Page page)
{
    if (null == page)
    {
        return;
    }
}

I did a double take and then smirked a bit, pointing out that this was probably dead code. I asked the person who was showing me this to do a “find all references” and there actually was one:

private void mainFrameNavigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
{
    Page page = e.Content as Page;
    if (page != null)
    {
        SetLayout(page);
    }
}

So, we then backed it up a step and discovered that this was an event handler for an event declared in XAML (this whole thing was in a code-behind file). So, every time some event occurred (some sort of navigation thing), the code would cast the sender as a page, call a method with that page, and then return if the page was null, and also return if the page wasn’t null.

How Did It Come To This?

Looking at the SetLayout method, I quickly developed a hypothesis as to how the code wound up this way. The “SetLayout” method probably checked the page for null as a precondition prior to performing some sort of action on Page. At some point, that action became undesirable and was removed from the code, but whoever removed it didn’t realize that the precondition check was now meaningless, as was the whole chain of code above it for the event handler. This was confirmed correct by a quick glance through source control.

Here’s what this looks like in my IDE:

Do you see the dashes on the right, next to the scroll bar? Those are the issues in the CodeRush “issues list”. Do you see the squiggly underline of “SetLayout” (hard to see at this resolution, but you can zoom in or open the image in a new tab if you want)? That means there’s an issue here. In the interests of full disclosure, this is actually to tell me that the method could be static (it operates on no instance member of the class) rather than to tell me that the method has no effect on anything, but the important thing is that it’s underlined. It draws my attention to the method instead of encouraging me to skip over it while looking for something else here. And, as soon as this method catches anyone’s attention, it will obviously be deleted.

The Value of Productivity Tools

In general, the Code Rush issues list is a great companion. It alerts me to dead code, undisposed disposables, redundant statements, and plenty of other things. If you pause any time it tells you about an issue, you will become better at programming and you will start to recognize more problems. It isn’t necessarily superior to using, say, Style Cop or any other particular tool, but it is very convenient in that it paints the problems right inline with the IDE. They’re quite noticeable.

Code Rush’s competitor, Resharper does this as well. I plug for Code Rush because I use it and I love it, but if you get Resharper, that’s fine — just get something. These productivity tools are game changers. When looking at this code in someone else’s IDE, there was no squiggly and no immediately obvious problem if you’re casually scrolling through the class. But in my IDE, my eyes are drawn right to it, allowing and in fact demanding that I fix it. This sort of boy-scouting makes you better at writing your own code and better at fixing other people’s.

I forget what the license costs, but your employer can afford it. Heck, if they’re too cheap, you can afford it. Because what you can’t afford is to have code checked in under your name that looks like the code in this post. That’s no good, and it’s avoidable.

By

C# Tips for Compacting Code

This is a little series of things that I’ve picked up over the course of time and use in situations to make my code more compact, and, in my opinion readable. Your mileage may vary on liking any or all of these, but I figured I’d share them.

To me, compacting code is very important. When I look at a method or a series of methods, I like to be able to tell what they do at a glance and drill into them only if it’s important to me. I think I naturally perceive code the way I do an outline in a Word document or something. I look on the left for brief, salient points, and then in the smaller text that goes further right only if I want to fill in the details. This allows me to variable skim over or delve into methods.

If methods are very vertically verbose, I lose this perspective. If I have two or even one method taking up all of the real estate in my IDE vertically, I don’t know what’s going on in the class because I’m lost in some confusing method that forces me to think about too many things at once. I don’t ever use that little drop down in Visual Studio with the alphabetized method list for navigation. If I have to use that to navigate, I consider the class a cohesion disaster.

So, given this line of thought, here are some little tips I have for making methods and code in general more compact without sacrificing (in my opinion) readability.

Null coalescing in foreach

Consider the following method:

public virtual void BindCommands(params ICommand[] commands)
{
    if (commands == null)
        return;

    foreach (var myCommand in commands)
         BindCommand(myCommand);
}

We’re going to take a collection of commands and iterate over them in this method, invoking an individual method to do the individual dirty work. So, the first thing that we do is guard against null so we’re not tripping over an exception. We could throw an exception on null argument, which might be preferable depending on context, but let’s forget about that possibility and assume that failing quietly is actually what we want here. Once we’ve finished with the early return bit, we do the actual, meaningful work of the method.

Let’s compact that a bit:

public virtual void BindCommands(params ICommand[] commands)
{
    var myCommands = commands ?? new ICommand[] { };

    foreach (var myCommand in myCommands)
       BindCommand(myCommand);
}

Now, we’re using the null object pattern and null coalescing operator to take care of the null handling, instead of an early return with an ugly guard condition. We can compact this even more, if so desired:

public virtual void BindCommands(params ICommand[] commands)
{
    foreach (var myCommand in commands ?? new ICommand[] { })
        BindCommand(myCommand);
}

Now, we’ve eliminated the extra code altogether and gotten this method down to its real meat and potatoes — iterating over the collection of commands. The fact that a corner case in which this collection might be null exists is an annoying detail, and we’ve relegated it to such status by not devoting 50% of the method’s real estate to handling it. The syntax here may look a little funny at first if you aren’t used to it, but it’s not double-take inducing. We iterate over a collection and do something. The target of our iteration looks a little more involved, but in my opinion, this is a small price to pay for compacting the method and not devoting half of the method to a corner case.

Using params

Speaking of params, let’s use params! In the method above, let’s consider the code that I was replacing:

private void BindCommand(ICommand command)
{
    if (command != null && _gesture != null)
        _window.InputBindings.Add(new InputBinding(command, _gesture));
}

Client code of this then looks like:

private void SomeClient()
{
    var myBinder = new Binder(SomeWindow, SomeKeyGesture);
    myBinder.BindCommand(SomeCommand1);
    myBinder.BindCommand(SomeCommand2);
    myBinder.BindCommand(SomeCommand3);
   //etc
}

As an aside, ignore the fact that it’s obtuse to bind a bunch of different commands to the same window and key gesture. In the actual code, there’s a lot more going on than I’m displaying here, and I’m trying to include nothing that will distract from my points. If you look at the params version above, consider what the client code of that looks like:

private void SomeClient()
{
    var myBinder = new Binder(SomeWindow, SomeKeyGesture);
    myBinder.BindCommands(SomeCommand1, SomeCommand2, SomeCommand3);
}

Now, I personally have a strong preference for that. A bunch of lines of the same thing over and over again drives me batty, even if the things in question need to be parameterized somewhere and this is the place it has to happen. There just seems something incredibly vacuous about code like the pre-example and I always favor more vertically compact code because I can process more of the details. By SomeCommand12, I’ve probably figured out what’s going on even on my slowest day — I don’t need another 50 lines besides. If we have to do things like this, let’s at least condense them so they take up as little mindshare in a method as possible.

Optional Parameters

If you haven’t gotten on board this train since C# 4.0, I’d say it’s time. If you have a bunch of code like this:

public void Method1()
{
    Method4(null, null, null);
}

public void Method2(string arg1)
{
    Method4(arg1, null, null);
}

public void Method3(string arg1, string arg2)
{
    Method4(arg1, arg2, null);
}

public void Method4(string arg1, string arg2, string arg3)
{
    Arg1 = arg1;
    Arg2 = arg2;
    Arg3 = arg3;
}

… it’s time to turn it into this:

public void TheOnlyMethod(string arg1 = null, string arg2 = null, string arg3 = null)
{
    Arg1 = arg1;
    Arg2 = arg2;
    Arg3 = arg3;
}

 

Omit brackets when you have a single line following a branch or loop condition

I used to be a stickler for this:

if(child.SpareRod())
{
    child.Spoil();
}

I reasoned that omitting the brackets was just begging for downstream maintenance problems, and that’d I’d be a good citizen, not taking shortcuts. I persisted in that way of doing things until quite recently. I was watching an Uncle Bob video where he said in passing, “I think that there should only be one line of code after an if or else or for, and I’m not going to make it easier on anyone that comes along to mess that up.” (can’t find the video, so I’m paraphrasing).

I blew this off at first, but for some reason, it stuck in my head and would occur to me from time to time. Finally, one day, I simply had a 180. I was now continuing to do it out of stubbornness, I realized, having long since decided Bob was right while barely realizing it. This practice made my code more compact, and it encouraged me to factor everything following a control flow statement into its own method, leading to much more readable code. I think the bigger benefit comes from the practice of “1 line per control flow statement” than the two lines you save from omitting the brackets, but nevertheless, both are adding up to create methods that are much more compact:

if(child.SpareRod())
    child.Spoil();

So, I’m out of tips for the day. If people like this, let me know, and perhaps I’ll put together another little post with a few more compactness tips, though it might take me longer to think of ones. These were low hanging fruit that I find myself doing often.

By the way, if you liked this post and you're new here, check out this page as a good place to start for more content that you might enjoy.

By

Mock.Of() and Mock.Get() in Moq

Today, I’d like to highlight a couple of features of Moq that I didn’t know about until relatively recently (thanks to a recent google+ hangout with Moq author, Daniel Cazzulino). Since learning about these features, I’ve been getting a lot of mileage out of them. But, in order to explain these two features and the different paradigm they represent, let me reference my normal use of Moq.

Let’s say we have some class PencilSharpener that takes an IPencil and sharpens it, and we want to verify that this is accomplished by setting the Pencil’s length and sharpness properties:

public void Sharpen_Sets_IsSharp_To_True()
{
    var myPencilDouble = new Mock();
    myPencilDouble.SetupProperty(pencil => pencil.IsSharp);
    myPencilDouble.Object.IsSharp = false;
    myPencilDouble.SetupProperty(pencil => pencil.Length);
    myPencilDouble.Object.Length = 12;

    var mySharpener = new PencilSharpener();
    mySharpener.Sharpen(myPencilDouble.Object);

    Assert.IsTrue(myPencilDouble.Object.IsSharp);
}

So, I create a test double for the pencil, and I do some setup on it, and then I pass it into my sharpener, after which I verify that the sharpener mutates it in an expected way. Fairly straight forward. I create the double and then I manipulate its setup, before passing its object in to my class under test. (Incidentally, I realize that I could call “SetupAllProperties()”, but I’m not doing that for illustrative purposes).

But, sometimes I’d rather not think of the test double as a double, but just some object that I’m passing in. That is, perhaps I don’t need to invoke any setup on it, and I just want to reason about the actual proxy implementation, rather than stub.object. Well, that’s where Mock.Of<>() comes in:

[TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
public void Sharpen_Sets_IsSharp_To_True()
{
    var myPencil = Mock.Of();
    myPencil.IsSharp = false;

    var mySharpener = new PencilSharpener();
    mySharpener.Sharpen(myPencil);

    Assert.IsTrue(myPencil.IsSharp);
}

Much cleaner, eh? I never knew I could do this, and I love it. In many tests now, I can reason about the object not as a Mock, but as a T, which is an enormous boost to readability when extensive setup is not required.

Ah, but Erik, what if you get buyer’s remorse? What if you have some test that starts off simple and then over time and some production cycles, you find that you need to verify it, or do some setup. What if we have the test above, but the Sharpen() method of PencilSharpener suddenly makes a call to a new CanBeSharpened() method on IPencil that must suddenly return true… do we need to scrap this approach and go back to the old way? Well, no, as it turns out:

[TestMethod, Owner("ebd"), TestCategory("Proven"), TestCategory("Unit")]
public void Sharpen_Sets_IsSharp_To_True()
{
    var myPencil = Mock.Of();
    myPencil.IsSharp = false;
    Mock.Get(myPencil).Setup(pencil => pencil.CanBeSharpened()).Returns(true);

    var mySharpener = new PencilSharpener();
    mySharpener.Sharpen(myPencil);

    Assert.IsTrue(myPencil.IsSharp);
}

Notice the third line in this test. Mock.Get() takes some T and grabs the Mock containing it for you, if applicable (you’ll get runtime exceptions if you try this on something that isn’t a Mock’s object). So, if you want to stay in the context of creating a T, but you need to “cheat”, this gives you that ability.

The reason I find this so helpful is that I tend to pick one of these modes of thinking and stick with it for the duration of the test. If I’m creating a true mock with the framework — an elaborate test double with lots of customized returns and callbacks and events — I prefer to instantiate a new Mock(). If, on the other hand, the test double is relatively lightweight, I prefer to think of it simply as a T, even if I do need to “cheat” and make the odd setup or verify call on it. I find that this distinction aids a lot in readability, and I’m taking full advantage. I realize that one could simply retain a reference to the Mock and another to the T, but I’m not really much of a fan (though I’m sure I do it now and again). The problem with that, as I see it, is that you’re maintaining two levels of abstraction simultaneously, which is awkward and tends to be confusing for maintainers (or you, later).

Anyway, I hope that some of you will find this as useful as I did.

By the way, if you liked this post and you're new here, check out this page as a good place to start for more content that you might enjoy.

By

Upgrading TFS from SQLExpress

Back Story

Some time back, I setup Team Foundation Server (TFS) on a server machine more or less dedicated to the cause. This was to test drive it to consider it as a replacement for legacy source control, requirements management, deployment, etc. Since it was a trial, run, I opted for keeping setup simpler initially, reasoning that I could expand later if I so chose. As a result, I didn’t bother with Sharepoint setup initially, and I allowed the default installation of a database, which was SQLExpress.

Once I got used to the features of the basic installation, I wanted to test out the more advanced ones, but this has proven annoyingly difficult. Setting up Sharepoint and trying to retrofit it on existing projects was an enormous hassle, and I wound up having to delete my old projects and ‘recrate’ them with Sharepoint. Granted, these were playpen sorts of projects, but there was actual work in them and they were useful — just not primetime. So, losing them would be a hassle. And besides, it’s kind of hard to fully test a system without using it to do something useful.

After letting the dust settle a bit on that annoyance, I decided I’d switch from SQLExpress to SQL Standard to get the full benefit of TFS reporting services (via SQL reporting services). This was another huge pain point, and I’m going to document below what I had to do. Basically, it involved backing up all the SQL Express databases, installing SQL Server 2008 standard, and importing those backups. This guide is by no means comprehensive and there are a lot of moving parts, so this isn’t exactly a walk through, but hopefully it will help save someone at least some annoyance in this battle and maybe shave a little time off. Read More

By

Introduction to C# Lambda Expressions

Today, I’m going to post an excerpt of a tutorial I created for the use of Moq on an internal company wiki for training purposes. I presented today on mocking for unit tests and was revisiting some of my old documentation, which included an introductory, unofficial explanation of lambda expressions that doesn’t involve any kind of mathematical lingo about lambda calculus or the term “first class functions”. In short, I created this to help someone who’d never or rarely seen a lambda expression understand what they are.

Lambdas


Since Moq makes heavy use of lambda expressions, I’ll explain a bit about how those work here. Lambdas as a concept are inherently highly mathematical, but I’ll try to focus more on the practical aspects of the construct as they relate to C#.

In general, lambda expressions in the language are of the form (parameters) => (expression). You can think of this as a mapping and we might say that the semantics of this expression is “parameters maps to expression”. So, if we have x => 2*x, we would say “x maps to two times x.” (or, more generally, number maps to number).

In this sense, a lambda expression may be thought of in its most practical programming sense as a procedure. Above, our procedure is taking x and transforming it into 2*x. The “maps to” semantics might more colloquially be called “becomes”. So, the lambda expression x => 2*x translates to “x becomes 2 times x.”

Great. So, why do this? Well, it lets you do some powerful things in C#. Consider the following:

public List FilterOut(List list, int target)
{
  var myList = new List();
  foreach(int myValue in list)
  {
    if(myValue != target)
    {
       myList.Add(myValue);
    }
  }
  return myList;
}

public void SomeMethod(List values)
{
  var myNewList = FilterOut(values, 6);  //Get me a list without the sixes.
}

Here, we have a function that will filter an int value out of a list. It’s a pretty handy function, since it lets you pick the filter value instead of, say, filtering out a hard-coded value. But, let’s say some evil stakeholder comes along and says “well, that’s great, but I want to be able to filter out two values. So, you add a method overload that takes two filters, and duplicate your code. They then come along and say that they want to be able to filter out three values, and they also want to be able to filter out values that are less than or greater than a specified value. At this point, you take a week off because you know your code is about to get really ugly.

Except, lambda expressions to the rescue! What if we changed the game a little and told the stakeholder, “hey, pass in whatever you want for criteria.”

public List FilterOut(List list, Func<int, bool> filterCriteria)
{
  var myList = new List();
  foreach(int myValue in list)
  {
    if(!filterCriteria(myValue))
    {
      myList.Add(myValue);
    }
  }
  return myList;
}

public void SomeMethod(List values)
{
  var myNewList = FilterOut(values, x => x == 6);  //Get me a list without the sixes.
  myNewList = FilterOut(values, x => x == 6 || x == 7); //Get me a list without six or seven.
  myNewList = FilterOut(values, x => x > 6 && x < 12); //Get me a list with no values between 7 and 11.
 //... and anything else you can think of that takes an integer and returns a boolean
}

Now, you don’t have to change your filter code at all, no matter what the stakeholder asks for. You can go back and say to him, “hey, do whatever you want to that integer — I don’t care”. Instead of having him pass you an integer, you’re having him pass you something that says, “integer maps to bool” or “integer becomes bool”. And, you’re taking that mapping and applying it to each element of the list that he’s passing you. For elements being filtered out, the semantics is “integer becomes false” and for elements making the cut “integer becomes true”. He’s passing in the mapping, and you’re doing him the service of applying it to the elements of the list he’s giving you.

In essence, lambda expressions and the mappings/procedures that they represent allow you to create algorithms on the fly, ala the strategy design pattern. This is perfect for writing code where you don’t know exactly how clients of your code want to go about mapping things — only that they do.

As it relates to Moq, here’s a sneak peak. Moq features expressions like myStub.Setup(mockedType => mockedType.GetMeAnInt()).Returns(6);
What this is saying behind the scenes, is “Setup my mock so that anyone who takes my mocked type and maps it to its GetMeAnInt() method gets a 6 back from it” or “Setup my mock so that the procedure MockedType.GetMeAnInt() returns 6.”

(By the way, the link I used for the visual is from this post, which turned out to be a great find. RSS feed added to my reader.)

By the way, if you liked this post and you're new here, check out this page as a good place to start for more content that you might enjoy.