Archive for November 2008

Mapping a shortcut to execute unit test in current context with ReSharper

It shouldn’t be a surprise to you that I’m a big fan of ReSharper since its early versions.  Its productivity boost and refactoring possibilities should alone convey a reason to learn and master it to be more effective when programming with C#. 

One thing that I wish came out of the box, but is currently missing, is a shortcut that allows me to run my unit test in the current context (by context I mean where my cursor is currently located.  If my cursor is currently in the body of TestA, then that shortcut will run the TestA unit test).  This will allow me to use the mouse even less, because right now I’m using the mouse to tell ReSharper to execute the current test. It turns out that though this functionality is lacking in ReSharper 4.1, the possibility to do so still exists. 

Here are the steps to follow if you want to map a keyboard shortcut that will run a test in the current context:

  1. In Visual Studio, go to Tools –> Options
  2. Expand the Environment node, then go to Keyboard
  3. In the commands list, search for Resharper.Resharper_UnitTest_ContextRun
  4. Assign a shortcut for that command.  In my case, I have decided to map it with Alt + X in the Global context.  That shortcut is intuitive (X for "execute”) and easy to trigger.  You can choose whatever mapping you want, just make sure there are no conflicts with other existing shortcuts.

Here’s a screenshot of the above steps in action:

image

Now you can place your cursor in a test context (test body or test method name) and hit that shortcut (Alt + X in my case) and that test will get executed.  A good tip to follow is to save your Visual Studio keyboard settings (and ReSharper settings too) under a backup repository (such as Live Mesh for example) so that you (or your team) can re-use those same settings in your Visual Studio sessions in other machines.

Being professional at work: an interview with Uncle Bob, Michael Feathers and Pete McBreen (JAOO)

I just finished watching a special interview with Robert “Uncle Bob” Martin, Michael Feathers and Pete McBreen (author of one of my favorite books “Software Craftsmanship”) that was recorded at last year’s JAOO (check out more JAOO videos here).  The subject is one my dearest and often misunderstood in the industry: being professional at work by writing clean code.  I’ve studied software engineering as an undergraduate and one thing that was clearly missing in the curriculum was a class or two about how to write good, solid, simple, clean code that works.  Instead we were taught a lot about software processes and how the processes determines whether or not your project will succeed.  That’s sad because deep inside I know that the process is the to support your project, not drive it.  What drives the project at the end of the line is the code.  Your software is ALL about code, not processes.

A couple of things that made me jump while listening to this interview were when Michael Feathers says that in one company, in which he consulted, none of the developers have heard of the “Design Patterns” book by the GoF.  Even a story that Pete McBreen told us about a developer who didn’t checked in his code after working on it more than four weeks.  This is a very important interview that the JAOO folks have made public and even more important for managers and developers to watch it together.  A special thanks for this discovery goes to Dave Hoover who started a thread on “apprenticeship” over at the Software Craftsmanship Google group.

 

Pluralsight’s screencasts on WCF, WF, AtomPub services, Oslo and more!

For your information, Pluralsight (a training firm specialized in Microsoft technologies) recently recorded some pretty useful screencasts about new and important .NET technologies such as WCF, WF, AtomPub services, Oslo and more.  These screencasts are available at no cost and is open to the public.  You can download these screencasts here.

Edsger Dijkstra on the “Discipline in Thought”

I first heard of Professor E.D. Dijkstra in an algorithm course during my undergraduate studies.  I’ve enjoyed reading his paper The Humble Programmer which he wrote as an acceptance speech for receiving a Turing Award in 1972.  While reading that paper, I couldn’t help myself to notice some key associations between what he suggested was needed to improve the art and science of software development and what the Agile philosophy was bringing forward.  I don’t want to go too much into the detail of that paper, but I strongly suggest you print a copy for yourself and read it.  Now to the essence of this post…I tend to get carried away sometimes…

A couple of years ago, Edsger Dijkstra was interviewed for sharing his thoughts on the discipline of programming.  For example, he mentions the beauty of code being measured in terms of quality, correctness and elegance.  That’s a key value which I hold tight in my heart when programming:  Always having that struggle with my ego, my mind and my intuition about how to write or change an implementation to make it just right…not perfect, but just right.  But what is just right?  See…that’s the kind of struggle I constantly have.  I love it.

While watching the interview, he seemed pretty sad or disappointed with the current state of computer science in the industry, as well as in the academia.  No doubt that we still have a long way to go to bring beauty in code, but I think that we have also make a strong progress since that first 1968 NATO conference on software engineering.  I believe that we’re living in exciting times in this industry.  I don’t know if Dijkstra would agree with that statement.  What do you think? 

NOTE: I came about this video from the most excellent blog of Peteris Krumins.

Sessions from PDC2008 now available!

This year’s Microsoft Professional Developer Conference is a thing of the past.  For those unlucky ones (like me) who didn’t attend this event, you can now have full and free access to the sessions and the keynotes.  Suddenly life just got better!

Mike Swanson has prepared for us a simple list of all keynotes and sessions by code and title from this year’s PDC.  This is some really cool stuff!

Remember that you can also browse the sessions by tag on the Channel 9 PDC 2008 page.

Now, let’s see what Azure is really all about…

Evolving your design with the Principle of Least Knowledge

One of the principles of object-oriented development is that you should strive for a design that favors low coupling among objects.  Given that change is constant in a software project, this principle provides many benefits when rightfully applied:

  • Code is easier to maintain because any change can be isolated to a very limited number of objects (hopefully only one)
  • Code is easier to use and reuse because your objects are not tightly related to a web of other objects
  • Code is easier to understand because we can focus on the behavior of a very limited number of objects (hopefully only one)
  • Code is easier to test because of the reasons stated above (it also reduces the use of mock objects in our tests which simplifies writing and maintaining them)

The last point is very important.  Code that is easier to test favors the writing of unit tests, which avoids potential bugs infesting the system, and embraces change as we have confidence in refactoring the codebase because our unit tests act as a safety net so that if we should brake something in the system, we’ll be notified in a short time…if the tests were well written of course, but that’s a subject for another post.

The Principle of Least Knowledge, also known as the Law of Demeter, is one of those principles which favor low coupling in your codebase.  The most excellent book “Head First Design Patterns” defines this principle as the following:

The Principle of Least Knowledge guides us to reduce the interactions between objects to just a few close “friends”.

But what does this mean in real terms?  It means when you are designing a system, for any object, be careful of the number of classes it interacts with and also how it comes to interact with those classes.

This principle prevents us from creating designs that have a large number of classes coupled together so that changes in one part of the system cascade to other parts.  When you build a lot of dependencies between many classes, you are building a fragile system that will be costly to maintain and complex for others to understand.  — “Head First Design Patterns”, pages 265-266.

In other words, this principle states that given an object, any of its method should only invoke methods that belong to:

  • The object itself
  • Objects passed in as a parameter to the method
  • Any object the method creates or instantiates
  • Any components of the object

Least but nonetheless important is another pointer which makes the whole difference (like spreading Nutella on whole wheat bread): methods should avoid invoking methods belonging to objects that were returned from some other call.

For example, you should avoid writing the following:.

public void DepositAmount(int accountId, double amount)
{
  Account account = bank.GetAccount( accountId );
  account.Deposit( amount );
}


And instead opt for this:

public void DepositAmount(int accountId, double amount)
{
  bank.Deposit( accountId, amount );
}

You should see that the latter implementation is easier to maintain, reuse, understand and test.  We haven’t changed the interface of the method, just its implementation.  This implementation is easier to reuse and test because we don’t have to rely on another external (whether concrete or abstract) object, in this case an Account, to fulfill the service.  We only have one object, the Bank, to deal with.

One of my mentors refers to this principle as the “Tell, don’t ask” principle.  It makes a lot of sense.  Alec Sharp, author of Smalltalk by Example, summarizes this principle in other words:

Procedural code gets information then makes decisions.  Object-oriented code tells objects to do things. — Alec Sharp

That was the theory behind the principle.  Let’s see a concrete and simple example which demonstrates what we should avoid and what we should strive for in our design.

This example doesn’t follow the Principle of Least Knowledge:

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var car = new Car();
      var driver = new Driver( car );

      driver.Car.Engine.Start(); // Not good.
                                 // Changing the signature of Start() will force to change
                                 // the callers too because of the strong coupling.
                                 // It also breaks the encapusalation of CarEngine because
                                 // the Driver knows too much about that class.
    }
  }

  class Driver
  {
    public Driver( Car car )
    {
      Car = car;
    }

    public Car Car { get; private set; }
  }

  class Car
  {
    private readonly CarEngine _engine;

    public Car()
    {
      _engine = new CarEngine();
    }

    public CarEngine Engine
    {
      get
      {
        return _engine;
      }
    }

    public class CarEngine
    {
      public void Start()
      {
        Console.WriteLine( "vroum! vroum!" );
      }
    }
  }
}


Whereas this same example does respect the Principle of Least Knowledge:

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var car = new Car();
      var driver = new Driver( car );

      driver.Car.Start(); /* Much better.  Why?
                             Now, we can also make CarEngine private to the Car class.
                             Even though CarEngine.Start is public doesn't mean we should
                             use it!  Here we decided to remove the Engine property in the Car
                             class.

                             With this approach, the Driver could care less HOW the Car gets
                             started.  Now, CarEngine can evolve on its own without impacting
                             the rest of the system.

                             In other words...just because there's a gun laying on the ground
                             outside Montreal East and it's past 2AM...doesn't mean you should
                             take it!  Not everything that's public is good to take.
                             */
    }
  }

  class Driver
  {
    public Driver( Car car )
    {
      Car = car;
    }

    public Car Car { get; private set; }
  }

  class Car
  {
    private readonly CarEngine _engine;

    public Car()
    {
      _engine = new CarEngine();
    }

    class CarEngine
    {
      public void Start()
      {
        Console.WriteLine( "vroum! vroum!" );
      }
    }

    public void Start()
    {
      _engine.Start();
    }
  }
}

As you can see from the preceding example, adopting the Principle of Least Knowledge in your design allows you to easily evolve other components in your system since they’re not tightly coupled with other components in other areas of the system.  In this instance, I can easily evolve CarEngine without impacting the rest of the system.  For example, I can change the way an engine is started.  Furthermore, I can even make the CarEngine class abstract, then have various implementations of it and still avoid rippling changes to my system.  The Principle of Least Knowledge gives me so much ease, flexibility and possibilities to evolve my design and test my system.

Using a tool like NDepend can help you to pinpoint locations in your code where coupling is strong so that you leverage this principle and step-by-step eliminate the unnecessary coupling among components.

In conclusion, I urge you to not get too personal with objects.  Don’t be too polite with them neither.  With people yes, but not with objects.  If you need an object to do something for you, tell it to do so.  Another variation of "tell" is "command".  Don’t tell the object to ask another object to do some job for you.  If you see that happening, you should remove the intermediate object and have the one that knows more about the underlying operation to execute the job for you.  In his book Applying UML and Patterns, Craig Larman refers to the Information Expert pattern for this kind of situation.  According to that pattern, you should "assign a responsibility to the information expert – the class that has the information necessary to fulfill the responsibility".

As you can see, there are many different interpretations for this principle.  Whether you know it as the Principle of Least Knowledge, the Law of Demeter or the Information Expert pattern, what’s important is that you understand and apply the essence behind it.  It’s all about doing object-oriented development right.