Oct 13 2011

Things Every Senior .NET Developer Should Know–Introduction

Category: Best Practices | .NETMatt @ 14:27

.NET will officially turn 10 years old in February.  Our platform and our community have matured and grown in that time, and today it is virtually impossible for a developer to truly be an expert in everything .NET-related.  There are, however, several things that I think everyone on the .NET platform, particularly those of us that are arrogant enough to call ourselves “senior” level, should know. 

Part 1 – Object-Oriented Programming

Over the coming weeks (or more likely, months, given how infrequently I manage to blog), I will share with you the things that I assume any senior-level developer in the .NET space is comfortable with.  If you are not familiar with these things, then now is your chance to really step up your game.  Each of these techniques and technologies are things that have aided me greatly in my career, and I think they’ll help you as well. 

I have my short list prepared, but before I dive in (beginning next post), I’d like to hear what others think.  What tools, techniques, technologies, etc. do you assume someone is familiar with when they say they are a “Senior .NET Developer?”

Tags:

Dec 15 2010

Using An Application Bus To Raise Events

Category: Best Practices | .NETMatt @ 14:38

I’ve been writing recently about the Application Bus pattern and how it’s used in RageFeed.  So far, I’ve shown you how it can be used to send both one-way commands as well as synchronous request-reply commands, enabling you to decouple the pieces of your application.  There’s another type of communication that is even more loosely coupled, and it’s a good fit for scenarios where you want to perform a variety of unrelated actions in response to something occurring in your application.  In this article, I’ll show you how to use the Application Bus to raise and handle events.

The Problem: A Violation Of Principles

Let’s look at a somewhat contrived example.  Suppose in RageFeed, when a new user registers, we need to create the user’s account, send the user a “Welcome” E-mail, send ourselves an E-mail, and send the user a free basket of goodies.  Here’s a possible implementation:

public class CreateUserHandler : IHandle<CreateUserRequest, CreateUserReply>
{
    ...

    public CreateUserReply Handle(CreateUserRequest request)
    {
        var user = new User {Username = request.Username, Email = request.Email};
        user.SetPassword(request.Password);

        _repository.Add(user);

        _dispatcher.SendNewUserActivation(request.Username, request.Email);
        
        _dispatcher.NotifyAdminsOfNewUserRegistration(request.Username);

        _fruitService.SendUserWelcomeBaseket(user);

        return new CreateUserReply {Succeeded = true};
    }
}

Even though we’re using Dependency Injection and leveraging the bus, we’ve still managed to violate several design principles in implementing this requirement. 

Single Responsibility Principle

The Single Responsibility Principle (SRP) states that a class should have exactly one reason to change.   In this case, our command handler actually could change for a lot of reasons.  The class would need to change if we decided to stop sending gift baskets, if we decide we don’t want to be notified when new users join, or if we decide we want to perform additional actions after a user registers.  And that leads us to our next violation…

The Open/Closed Principle

The Open/Closed Principle (OCP) states that classes should be closed for modification, but open for extension.  This means we should be able to add new functionality to an existing class without actually editing the class.  But how can we do that here?? One option would be to make the Handle method virtual, then derive a new class that adds new behavior, but that’s not a clean solution (remember, favor composition over inheritance, meaning look for ways to combine multiple independent classes rather than creating complicated inheritance hierarchies).

So, what can we do?  We need to perform several different actions after a user registers.  We know those actions may change in the future.  What can we do to support our requirements while not violating SRP or OCP?  The answer is simple: events! 

The Solution: Events

Let’s re-examine what our command handler should really be doing.  It should be performing the core “register user” action, and that’s it.  In this case, that means adding the user to the underlying repository.  All the other responsibilities are not part of our core process: the user is still registered even if we don’t perform them.  So,those auxiliary responsibilities are good candidates to refactor.  First, let’s add a new IRaiseEvents interface that our command handler can use to signal interesting events:

public interface IRaiseEvents
{
    void Raise<TEvent>(TEvent @event);
}

Next, let’s utilize this to signal that we’ve added a new user:

public CreateUserReply Handle(CreateUserRequest request)
{
    var user = new User {Username = request.Username, Email = request.Email};
    user.SetPassword(request.Password);

    _repository.Add(user);

    //_events is IRaiseEvents, injected by the IoC container. 
    _events.Raise(new UserRegisteredEvent {User = user});

    return new CreateUserReply {Succeeded = true};
}

Now, let’s add some event handlers to take over the responsibilities that used to live in our command handler:

public class UserActivationEmailSender : IHandle<UserRegisteredEvent>
{
    private readonly IEmailDispatcher _dispatcher;

    public UserActivationEmailSender(IEmailDispatcher dispatcher)
    {
        _dispatcher = dispatcher;
    }

    public void Handle(UserRegisteredEvent message)
    {
        _dispatcher.SendNewUserActivation(message.User.Username, message.User.Email);
    }
}

public class AdminNotifier : IHandle<UserRegisteredEvent>
{
    private readonly IEmailDispatcher _dispatcher;

    public AdminNotifier(IEmailDispatcher dispatcher)
    {
        _dispatcher = dispatcher;
    }

    public void Handle(UserRegisteredEvent message)
    {
        _dispatcher.NotifyAdminsOfNewUserRegistration(message.User.Username);
    }
}

public class WelcomeBaseketSender : IHandle<UserRegisteredEvent>
{
    private ISendFruit _fruitService;

    public WelcomeBaseketSender(ISendFruit fruitService)
    {
        _fruitService = fruitService;
    }

    public void Handle(UserRegisteredEvent message)
    {
        _fruitService.SendUserWelcomeBaseket(message.User);
    }
}

Now we can change what happens when a user registers without having to change our user registration command handler! Another nice benefit is that each action is now a lot easier to test and verify.

Extending the Application Bus With Support For Events

Our IRaiseEvents interface is implemented by the application bus.  We only need to make a few small changes to our existing code.  First, the bus:

public class ApplicationBus : IBus, IRaiseEvents
{
    ...

    public void Raise<TEvent>(TEvent @event)
    {
        var handlers = _registry.GetAllHandlersFor<TEvent>();

        foreach (var handler in handlers)
        {
            try
            {
                handler.Handle(@event);
            }
            catch (Exception ex)
            {
                //TODO: Log this somewhere, but don't rethrow.  The caller doesn't care!
            }
        }
    }
}

Next the registry:

public class MessageHandlerRegistry : IMessageHandlerRegistry
{

    public IEnumerable<IHandle<TMessage>> GetAllHandlersFor<TMessage>()
    {
        try
        {
            return _container.GetAllInstances<IHandle<TMessage>>();
        }
        catch (StructureMapException ex)
        {
            //202 means no suitable type found in the container. 
            if (ex.ErrorCode == 202)
            {
                return new IHandle<TMessage>[0];
            }
            throw;
        }
    }
}

It utilizes the same StructureMap-based conventions for registering event handlers, so we don’t have to make any changes there.  Our event handlers are registered automagically just like our command handlers!

Events or Commands?

Commands and events are handled very similarly with an application bus, so how do you decide if something should be a command or an event?  A command implies that exactly one handler will receive the command and do something with it.  In RageFeed, if you send a command and no one handles it, it’s an error.  Conversely, an event may not be handled at all.  It is handled by zero or more handlers, and the source of the event doesn’t care: it raises the event, then goes on about it’s business.  Events could be implemented asynchronously, even in an application bus, by spawning background threads for each event handler.  If you have event handlers that take a while to execute, this is something you should consider, and it’s an easy change to make should the need arise later.

This is a pretty barebones implementation of events.  If you wanted to go a little further, I’d recommend adding a base marker interface for your event classes to implement as well as your commands (on the grounds of making things explicit).   The error handling is also very primitive.  If an event handler throws an exception, the calling class doesn’t care, but you would definitely want to capture that information somewhere.


I think that covers it for events!  Use them when you want multiple handlers to perform actions that are not related to a core operation.  Like commands, they’re a great tool for creating loosely-coupled, easy-to-maintain code!

Tags:

Nov 14 2010

The Application Bus

Category: .NETMatt @ 07:03

The Message Bus pattern is a pattern of enterprise application architecture that deals with the integration of systems.  It consists of several components that facilitate the exchange of messages between the various systems in order to achieve some shared purpose.  When done properly, messaging is one of the lowest forms of coupling that can be achieved in a software system.  For this reason, it has become commonplace to use a message bus to decouple the components within a single logical application as well.  This use of the message bus pattern is so specialized that it is worthy of its own pattern name: the application bus. 

What is a message bus?

A message bus is a component that enables systems to communicate (often asynchronously) by passing messages indirectly to one another.  Examples of true message buses are NServiceBus, Rhino Service Bus, MassTransit, MSMQ, etc.  Note that these buses facilitate distributed communication across both logical and physical boundaries: messages may pass from process to process, from machine to machine, or perhaps even from network to network.  Most buses support two-way, synchronous messaging, but they are more commonly used in a one-way, asynchronous way.  Asynchronous one-way messaging can create systems that are a bit harder to understand (at least at first), but they are typically easier to scale, and they are easier to maintain due to the decrease in coupling (message passing is one of the lowest forms of coupling that can be achieved).

A recent trend, especially in the .NET community, is to custom build smaller-scale buses that facilitate the exchange of messages within a process boundary.  Instead of passing messages from system to system, buses are being used to pass messages from one instance of a class to another.  A common example may look something like this:

//Classes send messages to the bus through this interface...
public interface IBus
{
    /// <summary>
    /// Sends a message that doesn't require a response.
    /// </summary>
    /// <param name="message"></param>
    /// <typeparam name="TMessage"></typeparam>
    void Send<TMessage>(TMessage message);

    /// <summary>
    /// Sends a message and gets the reply. 
    /// </summary>
    /// <typeparam name="TRequest"></typeparam>
    /// <typeparam name="TReply"></typeparam>
    /// <param name="request"></param>
    /// <returns></returns>
    TReply RequestReply<TRequest, TReply>(TRequest request);
}

//Consumers implement one of these interfaces and are automatically
//registered with the bus, who then sends messages to the implementor
//as they arrive.
public interface IOneWayHandler<in TMessage>
{
    void Handle(TMessage message);
}

public interface ITwoWayHandler<in TRequest, out TReply>
{
    TReply Handle(TRequest request);
}

It is this later use that has become so specialized that it warrants its own pattern.  Unlike a typical message bus, these small-scale application buses often only support two-way, synchronous messaging and do not support sending messages across logical or physical boundaries.  They are often implemented by leveraging the capabilities of Inversion of Control (IoC) frameworks such as StructureMap or Ninject.   There are two consumers of the application bus’s services: message publishers, who create and send messages to the bus, and message consumers, who subscribe to handle messages based on message type.  This subscription is often handled by conventions configured through the IoC container. 

The Pattern, Defined

In order to be a true Software Design Pattern, the design pattern must meet a few requirements: it must solve a common design problem, it must be generally reusable, and it must be defined so as to be transformed easily into code.  The application bus definitely meets these requirements:

Problem: An application contains many classes that need to work together cohesively to achieve a shared goal.  How can these classes work together without succumbing to coupling problems?

Solution: Create an application service that enables the classes to work together by exchanging messages.

image

In the next post, I’ll show you how I implemented the application bus that powers the social networking application called RageFeed. 

Tags:

Jul 28 2010

Test-Driven Development – From Painful to (Near) Zero Friction

Category: .NET | TestingMatt @ 14:26

I don’t like development friction.  I especially don’t like testing friction.   Over the last several years, my approach to test-driven development and the style of test cases I create has changed drastically in an effort to eliminate testing frication.  To illustrate, I’ve created my first ever screencasts.  In these screencasts, I use TDD to implement a class in RageFeed.  Starting with very coarse, high-friction unit tests, I’ll show you how you can gradually reduce the friction by creating better tests.  Finally, I’ll show you how easy it is to create clean, readable, specification-style tests in RageFeed today.

Note: I apologize for the limitations of ScreenToaster’s player.  I’m in the process of mirroring the videos elsewhere, and I’ll update the post with links as soon as I get around to doing that.

In these screencasts, you’ll see me use a variety of tools.  They are:

Test-Driven Development - Part 1 (View)

In part 1, I introduce the class I’m going to be implementing, and I use TDD to flesh out the class.  I intentionally create my tests as I would have several years ago (meaning they suck).  From there, I gradually evolve them into a better suite of tests, but there’s still room for improvement.

Test-Drivent Development - Part 2 (View)

In part 2, I leverage some ReSharper templates and some base classes I’ve created in RageFeed to create replace my tests with behavior-driven development style specifications.  The result is (near) zero friction testing.

Downloads

I’ve packaged up the base SpecsFor<T> class as well as my ReSharper templates.  Feel free to use them for whatever you like! 

Download SpecsFor and ReSharper Templates: download

Questions? Comments?

I’m certainly not claiming that what we have in RageFeed is The One Way to do testing in .NET.  It works well for me, but I’d love to hear what others think.  Also, this is my first ever screencast, so please drop me a line and let me know what you liked, what you didn’t like, and what you’d like to see in future screencasts (assuming I actually do more).

Tags:

Jun 30 2010

RageFeed’s Message Bus

Category: .NETMatt @ 16:00

In my recent post about heavy controller actions in RageFeed, I promised to show more details about how the Message Bus pattern was being employed within RageFeed to facilitate the creation of simple, business-logic-free controllers.  Then I got sidetracked with a new job, CodeStock, travel, and life in general. Since then, the message bus in RageFeed has changed quite a bit.  In this post, I’ll show you how the bus looks today and how it’s implemented. 

As a refresher, recall that the controllers within RageFeed were becoming quite bloated, with code resembling the following:

private readonly IRageFeedMembershipProvider _membershipProvider;
private readonly IEmailDispatcher _emailDispatcher;
private readonly IProfileService _profileService;
private readonly IMembershipService _membershipService;

public SignupController(IRageFeedMembershipProvider membershipProvider, 
    IEmailDispatcher emailDispatcher, 
    IProfileService profileService, 
    IMembershipService membershipService)
{
    _membershipProvider = membershipProvider;
    _emailDispatcher = emailDispatcher;
    _profileService = profileService;
    _membershipService = membershipService;
}
...
public ViewResult Activate(string username, string activationToken)
{
    var profile = _profileService.GetForUser(username);

    if (profile == null || profile.ActivationToken != activationToken)
    {
        return View("ActivationFailed");
    }

    var user = _membershipService.GetUser(username);
    user.IsApproved = true;
    _membershipService.UpdateUser(user);

    return View();
}

By applying the message bus pattern, I was able to simplify the controllers to code that looked more like this:

private readonly IBus _bus;
private readonly IAuthenticationService _authService;

public SignupController(IBus bus, IAuthenticationService authService)
{
    _bus = bus;
    _authService = authService;
}
...
public ViewResult Activate(string username, string activationToken)
{
    var result = _bus.RequestReply<ActivateUserRequest,ActivateUserReply>(new ActivateUserRequest { Username = username, ActivationToken = activationToken });

    if (!result.Succeeded)
    {
        return View("ActivationFailed");
    }

    _authService.SetAuthCookie(username);

    return View();
}

While this isn’t a huge simplification in terms of lines of code, the improvements are still significant.  The business logic is gone and safely encapsulated somewhere on the far side of the bus.  Prior to the change, the tests had to setup expectations on mocks for both the profile service and the membership service.  After the change, the tests only need to setup the appropriate response from the bus.

The bus itself is quite simple:

public class MessageBus : IBus
{
    private readonly IMessageHandlerRegistry _registry;

    public MessageBus(IMessageHandlerRegistry registry)
    {
        _registry = registry;
    }

    /// <summary>
    /// Sends a message that doesn't require a response.
    /// </summary>
    /// <param name="message"></param>
    /// <typeparam name="TMessage"></typeparam>
    public void Send<TMessage>(TMessage message)
    {
        var handler = _registry.GetCommandHandlerFor<TMessage>();

        if (handler == null)
        {
            throw new HandlerNotFoundException(typeof (TMessage));
        }

        handler.Handle(message);
    }

    /// <summary>
    /// Sends a message and gets the reply. 
    /// </summary>
    /// <typeparam name="TRequest"></typeparam>
    /// <typeparam name="TReply"></typeparam>
    /// <param name="request"></param>
    /// <returns></returns>
    public TReply RequestReply<TRequest, TReply>(TRequest request)
    {
        var handler = _registry.GetCommandHandlerFor<TRequest,TReply>();

        if (handler == null)
        {
            throw new HandlerNotFoundException(typeof (TRequest), typeof (TReply));
        }

        return handler.Handle(request);
    }
}

It uses a registry to find appropriate command handlers, then dispatches the incoming message to the handler.  For request/reply scenarios, it returns the reply from the handler back to the original caller.  The registry is nothing more than a wrapper around StructureMap:

public class MessageHandlerRegistry : IMessageHandlerRegistry
{
    private readonly IContainer _container;

    public MessageHandlerRegistry(IContainer container)
    {
        _container = container;
    }

    public ICommandHandler<TMessage> GetCommandHandlerFor<TMessage>()
    {
        return _container.GetInstance<ICommandHandler<TMessage>>();
    }

    public IMessageHandler<TRequest, TReply> GetCommandHandlerFor<TRequest, TReply>()
    {
        return _container.GetInstance<IMessageHandler<TRequest, TReply>>();
    }
}

Note: I don’t like the names ICommandHandler and IMessageHandler, they’re going to be renamed soon(ish).

By leveraging StructureMap, command handlers can be automagically registered for the appropriate request/reply types, so adding and subscribing a command handler becomes as simple as creating a class that implements an appropriate interface:

public class CheckEmailAvailabilityHandler : IMessageHandler<CheckEmailAvailabilityRequest, CheckEmailAvailabilityReply>
{
    private readonly IUserRepository _repository;

    public CheckEmailAvailabilityHandler(IUserRepository repository)
    {
        _repository = repository;
    }

    public CheckEmailAvailabilityReply Handle(CheckEmailAvailabilityRequest request)
    {
        var isInuse = _repository.GetByEmail(request.Email) != null;

        return new CheckEmailAvailabilityReply {IsInUse = isInuse};
    }
}

Organizing the business logic this way makes it far easier to create small, reusable, easily-testable, and loosely-coupled nuggets of logic. 

One final note, I’m trying to follow the principles of the “onion architecture” as well as the “folder-per-feature” used by Ayende.  This means that each major feature in RageFeed will have it’s own folder (namespace) within Core, as illustrated below.

FeatureOrganization

I’m still not completely satisfied with this breakdown.  It feels “wrong” to have the messages living side-by-side with the handlers, but according to the onion architecture, it’s fine for the web layer to depend on core.  Even so, I’m considering breaking the message off into a separate namespace or project, but it does make it easier to find what you’re looking for when everything related to the implementation of a feature is contained in a single folder as it is now. If you have suggestions for better ways to organize things, please do share.

If you are familiar with MVCContrib, you should be wondering why I chose to implement my own bus instead of leveraging the bus that’s available in MVCContrib.  I have good reasons for that, but that’s a topic for another day.  In a future post (to be published sometime before the dinosaurs return in 2012), I’ll compare the RageFeed bus with the MVCContrib bus and highlight the pros and cons of each.  Until then, let me know what you think in the comments!

Tags:

May 17 2010

Heavy controller actions? The Message Bus Pattern to the rescue!

Category: .NETMatt @ 15:39

I recently derailed (badly) while working on a simple requirement for RageFeed: new user registration.  We decided to use the baked-in ASP.NET membership and profile providers, and I found myself adding a lot of code to facilitate the registration workflow.  This was a problem in and of itself, but I realized I had a bigger problem when I stopped and looked at the tremendous number of test cases for my controller.  I had drifted so slowly into a bad design that I didn’t even realize it was happening until it was too late.  Fortunately, all was not lost.  A design pattern from the distributed computing domain came to save the day.

RageFeed, the super-secret project that I have been only murmuring about from time to time for the last couple of months, is trudging along slowly.  Most of the infrastructure is in place and working, so work has turned towards implementing real, honest-to-goodness features.  The first thing I tried to tackle was new user registration; after all, what good are features without users to (ab)use them?  Our team decided that we wanted users to be able to get in and “raging” as quickly as possible.  The workflow would be like this:

  • User registers with their E-mail address and is given immediate (restricted) access.
  • A verification E-mail is sent to the user.
  • The user clicks a verification link that redirects to the system.
  • The system prompts the user to create a password.
  • The user is given full access to the system.

Knowing that the baked-in ASP.NET membership and profile providers were fairly rigid and not really all that well matched to ASP.NET MVC, we still naively assumed that we would be able to bend them to meet this non-standard workflow.  That was certainly a mistake in hindsight (which I’ll probably blog about later), but it led a bigger problem: bad code. In my push to “get the frickin’ users in the system”, I had lowered my guard and tried to brute force my way through the story.  I knew things were starting to go awry when the unit tests for the signup controller hit a dozen.  Sure, the user registration workflow is a bit complicated, but most of the complexity is business logic, not something that belongs in the controller. 

If I wasn’t so focused on “get it done, now”, I think I would have realized my approach was flawed from the beginning.  Some of the tests were difficult to write and required setting up expectations on multiple services.  This testing friction is usually a good sign that you need to rethink your approach.  In fact, I’d argue that a controller with more than a couple service dependencies needs to be redesigned anyway.  Coding to interfaces and using dependency injection does eliminate your coupling to concrete types, but the interfaces themselves still introduce coupling, and coupling should be kept to a minimum.

The Problem

Let’s look at the constructor for my original implementation of the SignupController:

private readonly IRageFeedMembershipProvider _membershipProvider;
private readonly IEmailDispatcher _emailDispatcher;
private readonly IProfileService _profileService;
private readonly IMembershipService _membershipService;

public SignupController(IRageFeedMembershipProvider membershipProvider, 
    IEmailDispatcher emailDispatcher, 
    IProfileService profileService, 
    IMembershipService membershipService)
{
    _membershipProvider = membershipProvider;
    _emailDispatcher = emailDispatcher;
    _profileService = profileService;
    _membershipService = membershipService;
}

Yep, it depends on *four* separate services.  At a minimum, this complexity could be hidden behind a facade, but there’s a deeper problem.  You can see it when you look at the Activate action:

public ViewResult Activate(string username, string activationToken)
{
    var profile = _profileService.GetForUser(username);

    if (profile == null || profile.ActivationToken != activationToken)
    {
        return View("ActivationFailed");
    }

    var user = _membershipService.GetUser(username);
    user.IsApproved = true;
    _membershipService.UpdateUser(user);

    return View();
}

See that?  It’s subtle, but it’s there, hiding in plain sight: business logic.  The controller now knows the rules for how a user can be activated (their activation token must match the previously stored activation token) and how to activate them (setting the IsApproved flag to true).  As I was TDDing this method, I created three separate test cases: one to test for a non-existent user (null profile), another for an invalid activation token, and finally one to verify that the user is correctly activated.  Each required at least some setup on the mock services.  This same sort of business logic leak occurred in some of the other signup-related actions, leading to a large test fixture and code that made me cringe. 

The Solution

Instead of containing business logic, my controller action should do nothing more than get data from (or provide data to) the views, and pass it off to the business layer of the system for further processing.  The controller should handle things like user-input validation (via model binding) and determining which view to render, but it shouldn’t make business decisions.  Thinking in very generic terms, the controller should publish a command to the business layer, and something in the business layer that subscribes to the command should process it, returning only the information the controller needs to decide which action result to return.  This is about as loosely coupled as you can realistically get: the controller shouldn’t know (or care) who is processing the command, and the class processing the command shouldn’t care about where the command comes from.

There’s a Pattern For That: the Message Bus. While this pattern has historically been used for communication between applications in a potentially distributed environment, it has gained ground recently as a means of decoupling components within the same physical application.  The MVCContrib project includes a message bus, and numerous blog posts of late have presented various incarnations of this pattern. 

Ignoring how RageFeed’s message bus works, take a look at the revised implementation of the Activate action now:

public ViewResult Activate(string username, string activationToken)
{
    var command = new ActivateUserCommand {Username = username, ActivationToken = activationToken};

    var result = _bus.Send(command);

    if (!result.Succeeded)
    {
        return View("ActivationFailed");
    }

    return View();
}

What was gained?

The action is simpler now, and more importantly, it is completely devoid of business logic.  It just creates the command, sends it, gets the response, and decides which view to render.  No longer is the controller coupled to multiple services, instead it has just a single dependency on the message bus, and that’s it.  The corresponding tests are also simpler: they just need to verify that the expected command was sent, and that the correct view was rendered for both success and failure.  They don’t need to setup expectations on anything except the service bus.  Note that I really didn’t remove any business logic from the system, I just (correctly) encapsulated it in the business layer, leaving the controller free to focus on user interface-related concerns. 

So how does it work?

Good question!  I’ll dive into the details of how the bus is implemented and how the command processor for the ActivateUserCommand is implemented in the next post!  In the meantime, let me know what you think in the comments.

Tags:

May 13 2010

Want to be a better developer?

Category: Best Practices | .NETMatt @ 06:44

I've been trying to put together a link list of things that have helped me improve as a developer over the last couple of years.  This is far from complete, but it's a start.  I'm not saying this is an absolute "you have to know these things" list or that it will work for everyone out there, it's just things I've found to be really helpful for me.  As always, your mileage may vary. 

  • SOLID Principles - These principles have helped me a ton.  They aren't rules to be followed blindly, but I've found that understanding the reasoning behind them and trying to strive for code that adheres to them generally makes things easier (and also more fun) in the long run.  Now when I’m faced with a design choice, I usually ask myself which alternative is more SOLID and go with that.  Be sure to check out the SOLID “motivational” posters over at Derick Baily’s blog.
  • Design Patterns – Certain types of problems tend to recur in software development.  For these, we have design patterns.  Getting a handle on design patterns is something that only comes with practice.  You won’t be able to memorize and recognize even the “core” set of patterns immediately, but over time you will likely find yourself recognizing when to apply them more and more often. I strongly recommend Head First Design Patterns (yes, the code samples are in Java, but the patterns themselves are what’s important, and a C# dev should have no problem following along).  It provides a very good introduction to design patterns.
  • Test Driven Development – I think a lot of new developers hear “testing” and immediately glaze over, but I actually enjoy practicing TDD.  It doesn’t just help me test my code, it helps me design my code.  That’s a big advantage that a lot of people overlook.  It also gives me confidence that the class I’m creating does exactly what it is supposed to do, and nothing more.  If you aren’t sure how to do TDD, you can watch one of the various TDD Katas online, such as the String Calculator at Roy Osherove’s site or the Bowling Game at ‘Uncle’ Bob’s site. 
  • Resharper 5 - Resharper is essential for doing C# development in my opinion.  Out of the box, it will suggest lots of little things that can help improve your code.  It helped me learn LINQ by offering to convert ugly for/foreach loops into clean, elegant LINQ expressions, and it finally convinced me that ‘var’ isn’t always evil. 
  • NHibernate and FluentNHibernate - I prefer NHibernate to Castle ActiveRecord these days; the ActiveRecord pattern isn't as flexible or as extensible as an implementation of the repository pattern based on NHibernate, and I’ve run face first into that wall on more than one occasion.  FluentNHibernate makes it a lot easier to get up and running with NHibernate since it hides the XML and provides other nice helpers to get you started.  
  • Lambda expressions - These are essential when working with C# 3.0 or later.  They're a bit hard to grasp at first, but they open up very interesting re-use possibilities, and lots of APIs leverage them heavily. FluentNHibernate uses them to setup mappings, and StructureMap uses them for its embedded Domain-Specific Language (DSL). 
  • Generics - This is an older C# feature, but understanding generics is still just as essential today as ever.  Beyond leveraging the built-in generic classes from the base-class library, learning to wield generics also opens up new avenues for creating clean, extensible, and reusable classes.
  • StructureMap (including its AutoMocking container) - One of the biggest "lightbulb" moments I've had recently was adopting StructureMap and IoC-everywhere.  This totally changed how I code.  Now when I realize a class I'm working on is going to need some other 'service' to fullfill its responsibilities, I simply create a new service interface and add it to my class's constructor.  This makes doing top-down development much easier.  Once I’ve finished the tests and implementation for the class I’m working on, I can turn my attention to creating the class that fullfills the service interface. 
  • LINQ - A lot of people focus on LINQ to SQL, but LINQ is more than that.  LINQ to Objects is incredibly useful. Instead of complicated foreach loops that filter or project objects, I find myself writing short, elegant LINQ queries instead. Be sure you learn about all the various extension methods and keywords, including things like ‘select…into’ and ‘let’. 
  • Moq – Mocking frameworks allow you to configure stubs or fakes that you can substitute for dependencies while testing your classes.  While they can indeed be abused, they are still quite useful.  Moq is my personal favorite for its fluent, lambda-based syntax.  Combine it with the adapter pattern, and you can even use it to fake or stub dependencies on base-class library types.
  • ASP.NET MVC and MVCContrib – If you are going to make an ASP.NET application, do yourself a favor and go the MVC route.  While the drag-and-drop appeal of WebForms can be hard to resist, you will inevitably find yourself fighting its leaky abstractions and lack of flexibility as your application scales.  Out of the box, ASP.NET MVC is still quite bare-bones, and you may find yourself having to focus on issues that are more “plumbing” and less “application”.  Be sure to check MVCContrib before you start reinventing the wheel.  With things like portable areas, fluent control builders, test helpers, and a slew of HtmlHelper extensions, it’s surprisingly easy to build maintainable, testable ASP.NET applications by leveraging MVCContrib and ASP.NET MVC. 

Aside from that, I also follow numerous blogs on development.  If I had to trim Google Reader down to only two dev blogs, they would probably be:

  • Ayende @ Rahien – Creator of more open-source .NET software than probably anyone, Ayende is one of my “code heroes”.  I’ve learned a lot from his blog and by reading the code of his various projects.
  • Los Techies – The number of really smart people blogging here makes it a must-read.  I’ve absorbed a lot of new ideas and information from this place.  

I’m sure I’m overlooking something.  Let me know what you’ve found most helpful in improving your developer chops in the comments.

Tags:

Mar 11 2010

Two things missing from C#

Category: .NETMatt @ 08:07

While building some ugly code to walk the Lucene.NET Query graph, I found myself needing two bits of functionality from C# that it sadly doesn’t provide.  There are arguments for and against each of these, but they certainly would have saved me some pain today.

Switching off of System.Type

The Lucene query graph is a nasty beast.  There’s an abstract base Query class, but no common way to iterate through the graph and extract criteria.  Instead, you have to process each concrete type separately.  An easy way to do this would be to use a switch statement off of the concrete query type and execute the corresponding logic to process the type.  Unfortunately, the C# switch statement only supports types that are convertible to Integer (and strings).  There are solutions, such as this, but why isn’t it built in to the framework?  Peter Hallam explains the reasons, but I don’t agree with most of his argument. Visual Basic’s equivalent of a switch statement allows for case statements to “overlap”, and it doesn’t seem to be causing catastrophic problems there.  I think it’s actually quite intuitive to expect that only the first matching case statement would be executed.  In any case, I’d love to see this added to C#.

Using ‘yield return’ to directly return an IEnumerable

The ‘yield return’ statement is incredibly useful, but I’ve found myself on multiple occasions using it to enumerate a hierarchical object graph.  In such situations, it’s quite annoying that I can’t just ‘yield return’ the entire child object IEnumerable list at once.  Instead, I have to manually iterate the child list and ‘yield return’ each result individually.  I see no reason (at all) why this extra step should be necessary.   Wes describes a possible way to implement this feature, and there’s a (closed as won’t fix) issue on Microsoft Connect with a slew of votes.

Tags:

May 7 2009

Simplified unit testing for ASP.NET MVC JsonResult

Category: MVC | .NETMatt @ 01:45

There are quite a few examples floating around on the web that describe how to test your JsonResult objects to make sure the data was correctly packaged.  They all follow the same basic pattern: mock out core ASP.NET objects (such as ControllerContext, HttpResponse, and HttpContext), call JsonResult.ExecuteResult, recover what was written to HttpResponse.Output, and deserialize it.  Sure, this approach works, but in the same manner as cleaning your house out by lighting it on fire.  It’s way overkill.  There’s a much easier way.  For simple objects, just cast JsonResult.Data:

   1: string value = "Hello, there!";
   2:  
   3: JsonResult result = new JsonResult { Data=value };
   4:  
   5: //SURPRISE!
   6: Assert.AreEqual(value, (string)result.Data);

Yeah, that seems fairly obvious.  You don’t even need the explicit cast there, I just threw it in to prove the point.  But what about anonymous types?  Easy:

   1: var value = new { Id=5, Something="Else" };
   2:  
   3: JsonResult result = new JsonResult { Data=value };
   4:  
   5: IDictionary<string,object> data = new RouteValueDictionary(result.Data);
   6:  
   7: Assert.AreEqual(5, data["Id"]);
   8: Assert.AreEqual("Else", data["Something"]);

See, easy! “But what about arrays of anonymous types?!?!?” Do not fret, LINQ to the rescue:

   1: var values = new[]
   2:                  {
   3:                      new { Id = 5, Something = "Else" },
   4:                      new { Id = 6, Something = "New" },
   5:                      new { Id = 7, Something = "Old" },
   6:                  };
   7:  
   8: JsonResult result = new JsonResult { Data = values };
   9:  
  10: IDictionary<string, object>[] data = ((object[]) result.Data).Select(o => new RouteValueDictionary(o)).ToArray();
  11:  
  12: Assert.AreEqual(5, data[0]["Id"]);
  13: Assert.AreEqual(6, data[1]["Id"]);
  14: Assert.AreEqual(7, data[2]["Id"]);
  15: Assert.AreEqual("Else", data[0]["Something"]);
  16: Assert.AreEqual("New", data[1]["Something"]);
  17: Assert.AreEqual("Old", data[2]["Something"]);

Again, easy!

Alright, I know what you’re thinking.  “But Matt, the other solutions are all way more complicated, plus you’re cheating, that isn’t what JsonResult.ExecuteResult is going to do!” Well, you’re half-right, the other solutions are way more complicated, but this is actually simulating precisely what ExecuteResult will do.  Don’t believe me?  Pop it open in Reflector, or just browse the source (man I love Subversion).  It isn’t doing anything magical, it’s just using JavaScriptSerializer.  My solution just cuts out the middle man and doesn’t require you to mock out a bunch of complicated objects.

Tags:

Mar 18 2009

First Impressions of Resharper 4.5

Category: .NETMatt @ 03:05

Well, I broke down and installed the new beta of Resharper a few minutes ago.  This was motivated by the fact that I was working with our gigantic DAL, and 4.1 was really slowing me down (like it always does on large files).  Resharper 4.5 didn’t boast improvements for large files, just large solutions, but I thought I’d try it anyway. 

So, first thing I notice is that the solution (about 50 projects) opens slightly faster, maybe.  It was really too close to tell without using a stopwatch.  Color me not impressed. 

Next, my Agent Smith plug-in was gone.  It’s a really handy plug-in, so I checked the site, saw that there was a version for 4.5, uninstalled my old 4.1 version of the plug-in, installed the 4.5 version, and thought I would be good to go.  WRONG.

Resharper puked on load with this error: Could not load type
'JetBrains.UI.Shell.PluginSupport.PluginDescriptionAttribute' from
assembly 'JetBrains.Platform.ReSharper.UI, Version=4.5.1182.15,
Culture=neutral, PublicKeyToken=1010a0d8d6380325'
.  Looks like Agent Smith doesn’t work with the beta.  Fortunately, someone has already posted fixed binaries here.

Now, all seems well.  I load the DAL back up, but I’m very disappointed to see that performance has not improved much.  Even typing in such a large file causes all kinds of slowness.  It appears to be a little better than 4.1, but it’s hardly noticeable.

Oh well, I still love Resharper.  It’s a great product.  I guess I just expected/hoped for a little more out of a release that was focused on improving performance.

Tags: