Brendan Enrick

Daily Software Development

Static Mocking with JustMock

One of the coolest (and scariest) things I’ve seen lately is mocking static classes and methods with JustMock. I was working on some legacy code, and was making some changes, so I wanted to make sure that I got everything tested first. When I went to write the tests, I noticed that I needed to wrap and hide away a static method that was being called.

My eventual intent, however, is to get rid of the static class and method calls if possible. Writing the wrapper around it temporarily, so I can get tests in place before refactoring has always seemed like a pain. I went to check and see if JustMock would be able to mock a static class. That seemed like one of those crazy things that commercial mocking frameworks can usually do. I was right. It could mock the static class. (SCARY!!)

I wrote some code that looked like this: (Sorry I can’t show you my clients’ code in my blog without their permission, so you get sample code.)

public static class MyStaticClass
    public static int DoSomeDependentStuffThatIsHardToFix()
        // Pretend this does more than just returning 1
        return 1;


In my example, I need to test some code calling this static method. Normally, I would put a wrapper around this class, write my tests, refactor, and eventually change this to not be a static dependency anymore.

I decided to try this. Here is a test class that uses mocking to demonstrate how I can decide any result for this method and have control of this dependency. Notice that my method always returns 1. Pretend that a different result were possible.

Now when I go to write my test, I can just Mock out the static and define that I want that method to be called and for it to return 2 instead of 1. I will then assert that it worked as I expected in my test. Once I confirm that the mock works as expected using this type of test, I can put it in place in my actual test. (Yes, I sometimes write temporary tests to confirm what I expect before I write the whole test. Little steps.)

public class MyTestClass
    public void WhatIsTestedDoesNotMatter()
        Mock.Arrange(() => MyStaticClass.DoSomeDependentStuffThatIsHardToFix()).Returns(2);
        Assert.AreEqual(2, MyStaticClass.DoSomeDependentStuffThatIsHardToFix());

Then when I go and run my tests, I get this nice result showing me that everything is working as I expect it to. Yippee!

JustMock Static Test Passing

How it achieves this? I am not sure. I intend to find out though. When I do, I will write a post explaining it.

Have a good day!

Open/Closed Principle and Reinventing the Wheel

This month at the Hudson Software Craftsmanship group, we had two interesting discussions that were spawned from the NimblePros Software Craftsmanship Calendar. The calendar’s topic for March 2011 was the Open/Closed Principle and the topic for March 2012 is Reinventing the Wheel. Keep in mind that 2011 is a calendar of good practices we want to encourage and the 2012 calendar is full of anti-patterns to be avoided.

This post is a recap of some of the stuff we discussed at the March, 2012 HudsonSC meeting.

Reinventing the Wheel

Going into the meeting, I had the thought that Reinventing the Wheel is obvious when you’re doing it and Open/Closed is less obvious when you’re not following it. Boy was I wrong. The main discussion we had about Reinventing the Wheel was based on “how do I avoid reinventing the wheel in a large, badly organized code base”. We had a lot of very good ideas and suggestions about how we can try to avoid this through tools, communication, and a variety of other methods and ideas. It’s interesting though, because none of them really are the silver bullet that just solves this challenge. If you don’t know if something is already written in the codebase, it can be a real challenge to find.

Open/Closed Principle

For the open closed principle, we discussed how we use it, when it’s used, and whether we should start of our code building for open/closed. I think most people came to the consensus that it’s likely not a good idea to use Open/Closed right away, but that we should refactor to it when we’re changing the code. The thought here is that if we change it once, we might need to change it again, so the next time we need to extend it instead of changing it.

Make the code better now and we’ll save ourselves time later.

Supermarket Checkout Exercise

As our programming exercise at the end of the day, we decided to do the Supermarket Checkout programming exercise. It is an interesting little challenge that involves some design decisions. This is what makes it interesting.

The exercise has the developers writing a checkout system for a supermarket. Essentially, it’s about calculating the price of the items as their scanned. It factors in discounts, selling by quantity or individually, and selling by weight. This information also needs to be presented to the customer on a receipt at the end of the transaction. This means that you need to figure out how to give the user the needed information in a nice, clean way.

As you work on the code, you have to make some decisions on how the code is going to interact with the customer. Should the discounts appear inline immediately or at the end? Is the discount a separate line item or shown in the price? How do these choices affect how you’re writing the code? Some have you returning information immediately and some have you gathering the information later. How do you adjust your design decisions based on this?

You can find a link to this programming exercise and more on my List of Katas and Programming Exercises. And, because I am not a total jerk, I will give you a direct link to the kata pdf in case you don’t want to check out my other blog post.

Supermarket Pricing Coding Exercise (Sample Output)

The Sample Output is optional to use. You can also come up with any sample output that you wish to use for it. Change things up. Or do the kata and then pretend that the business rules have changed and now you need to display the information differently.

Good Teams Focus on the Team

I believe there are two main types of “teams”: those working together, focusing on doing their best as a team and those working individually, focusing on doing their best on their own. (Yes, some teams are in between.)

I think you can guess based on my wording of those two options, that I prefer working as a team toward a combined goal. By working together, we can accomplish much more. We must be careful along the way, however, to make sure that we don’t do anything that can hurt the teams abilities to work as a team.

Building a good, cohesive team is my greatest achievement in my software development career. Being a part of this team as it achieves great things is what I have received in return. – Brendan Enrick (March, 19, 2012)

I am always trying to make sure that the team is doing well. I try to keep them focused and working together. Most of all, I try to make sure that the things I do don’t hurt the team. It’s important to recognize that decisions and choices we make affect the team a great deal.

Building strong teams requires a lot of work. This post focuses on considerations that I believe are important to creating strong teams. These considerations include: communication, co-location, combined interest, respect, and commitment consensus. I focus on these when trying to create good, cohesive teams.


Creating great software depends heavily on communication. This is important for the whole team. It’s important that all members of the team be communicating with all other members of the team. If communication breaks down, the team is soon to follow.

It’s important for the whole team to be talking, writing, documenting, and sharing their ideas. Make sure that your team feels safe working together and communicating with each other.

Communication is so obvious as an important aspect of a good team, that I am not going to spend a great deal of time discussing it.


There is no easier way of getting a team to work together than to have them located together. Keeping the team close together keeps communication high. Not only does this mean that asked questions will be answered quickly, it also means that questions will be asked. If the team were not together, someone might not have asked the question. This keeps the communication barrier low and the feedback loop short.

I said this was an easy thing to achieve, and it can be. Sometimes there are difficulties with logistics of your space, people not wanting to move, etc. These can happen and can also be worked through. If you don’t have a team room, you can still set up a “command center” in an unused conference room.

I’ve seen both introverts and extroverts do well in co-located teams. When the conversation is on-topic it allows everyone to tune in to what the team is doing. The team will start answering questions immediately, knowing what everyone else is working on, chiming in with assistance on an area of expertise.

Great teams work together

Combined Interests and Goals

It’s extremely important that a team have a shared goal. If you fragment the goals of your “team”, you will be fragmenting the “team”. You run the risk that the team will have no incentive to work together. Yes, you might say that since everyone gets along, they’ll work together still, but you’re driving in a wedge that will pull them apart.

I don’t want my team to have individual goals, this will cause them to work on their own and make it harder for them to work together. Anyone spending their time helping someone else would be in danger of not finishing their own work, but I want them working together to achieve more.

Nothing is as detrimental to a team than making them behave less like a team.

By combining the goals and interests of the team, you force them to work together. They get the idea that they’re being graded together and being rewarded together. This will keep everyone on the team at  their most productive, because they will all have each other to lean on.


This word gets four uses here. It is important that members of a team treat each other with respect, it is important that members of a team respect each other, it is important that each member respects oneself, and it is important that everyone respect the code being written.

If one member of the team doesn’t respect another of the team members, the team will not be cohesive. If one member of the team doesn’t show respect to one or more members of the team, the team will not be cohesive.

If one member of the team doesn’t respect oneself, the team will not be cohesive. If one member of the team doesn’t respect the code being written, the team will not be cohesive.

When the team has respect for each other, they will strive to not hinder the rest of the team. This means that they will try not to break the code base. They will try to make sure that they build good, simple designs that everyone can appreciate. And communication will also flourish.

When the team has respect for themselves and the code they’re writing, they will strive to write clean, simple, well-tested code. The team will care about the work they’re doing and will avoid creating a big messy codebase.

Commitment Consensus

Making any commitment as a team must be done with a consensus among the group. One of the worst things that can be done to a team is to set their commitments for them. You can’t tell someone else what they are required to commit to.

Commitments have to be made willingly or the commitment might as well not be made at all.

This mistake is commonly made by people assigning work for the team to work on without getting their feedback on it. If you assume that a team can get X amount of work done without asking them, you’re asking for trouble. First, you’re making their decisions for them. This is going to make you into the opposition of the team. Second, you’re not soliciting their opinions or feedback.

Often this means that someone who is not going to be doing the work has estimated the time the work will take to complete and has assigned this work to individual team members. This will break the combined interest, encourage the team to break from their co-location, and cause the team to feel the person making those decisions isn’t taking them into consideration.

The right way is to work with the team. If you do need a commitment on something, you should work with the team to create that commitment. This usually means sitting down and working with them on it. Get them to decide what they can accomplish in an amount of time. Work with them to decide what will be worked on. This means that the person deciding the direction of the project should be directly talking with the development team doing the work.

Getting people together, working together, collaborating, is what makes teams effective. Don’t try to force them into doing something they don’t want to do. It will backfire on you. Plus, they’re likely not going to uphold that commitment. It wasn’t their commitment anyway. Not really.

The Team

If you manage to get the team working together effectively, keep it up. Try new things, but don’t let it destroy the team. If it looks like it’s hampering the team’s togetherness, quit doing it. Find another way of doing whatever you’re doing.

Don’t force the team into processes they don’t like. Let them create a process that works for them. Give them the tools and enable the team to make the right choices. Empower your team! Make sure that you never become the opposition of the team. Try to be part of the team. Align your interests with theirs.

Coding Katas and Exercises

The following post is a list of useful practicing resources. These include: coding katas, programming exercises, and educational software development games.

If you’re not sure why you should be doing coding katas and exercises, I have this old post explaining the benefits of coding katas.

Coding Katas


  • Agile Ball Flow Exercise (imagine the 1990s under construction gif here)
  • Agile Pizza Shop (imagine the 1990s construction gif here)
  • Marshmallow Challenge (imagine the 1990s construction gif here)

Recap Posts About Katas, Exercises, and Games

Fun with IL DASM and Duck Typing

So as a bit of fun, since I just wrote a post about duck typing and foreach loops, I thought I would take a look at what’s happening under the hood when we use this trick. To start with, I will have two classes, which each have GetEnumerator methods. The first one is using DuckTyping, so it doesn’t implement any interfaces. The second one is implementing the IEnumerable interface. Finally, I have a third class with a method that just uses a foreach loop over instances of the other two classes.

The code for my little example looks like this:

public class DuckCollection
public IEnumerator GetEnumerator()
throw new NotImplementedException();

public class EnumerableCollection : IEnumerable
public IEnumerator GetEnumerator()
throw new NotImplementedException();

public class ForEacher
public void DoForEach()
var duckCollection = new DuckCollection();
foreach (var thing1 in duckCollection)


var enumerableCollection = new EnumerableCollection();
foreach (var thing2 in enumerableCollection)


After I compile this code, I’ve opened it up with IL DASM, so I can see what the generated IL is for this code.
.method public hidebysig instance void  DoForEach() cil managed
// Code size 146 (0x92)
.maxstack 2
.locals init ([0] class DuckTypingILCode.DuckCollection duckCollection,
[1] object thing1,
[2] class DuckTypingILCode.EnumerableCollection enumerableCollection,
[3] object thing2,
[4] class [mscorlib]System.Collections.IEnumerator CS$5$0000,
[5] bool CS$4$0001,
[6] class [mscorlib]System.IDisposable CS$0$0002)
IL_0000: nop
IL_0001: newobj instance void DuckTypingILCode.DuckCollection::.ctor()
IL_0006: stloc.0
IL_0007: nop
IL_0008: ldloc.0
IL_0009: callvirt instance class [mscorlib]System.Collections.IEnumerator DuckTypingILCode.DuckCollection::GetEnumerator()
IL_000e: stloc.s CS$5$0000
IL_0010: br.s IL_001c
IL_0012: ldloc.s CS$5$0000
IL_0014: callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
IL_0019: stloc.1
IL_001a: nop
IL_001b: nop
IL_001c: ldloc.s CS$5$0000
IL_001e: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
IL_0023: stloc.s CS$4$0001
IL_0025: ldloc.s CS$4$0001
IL_0027: brtrue.s IL_0012
IL_0029: leave.s IL_0048
} // end .try
IL_002b: ldloc.s CS$5$0000
IL_002d: isinst [mscorlib]System.IDisposable
IL_0032: stloc.s CS$0$0002
IL_0034: ldloc.s CS$0$0002
IL_0036: ldnull
IL_0037: ceq
IL_0039: stloc.s CS$4$0001
IL_003b: ldloc.s CS$4$0001
IL_003d: brtrue.s IL_0047
IL_003f: ldloc.s CS$0$0002
IL_0041: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_0046: nop
IL_0047: endfinally
} // end handler
IL_0048: nop
IL_0049: newobj instance void DuckTypingILCode.EnumerableCollection::.ctor()
IL_004e: stloc.2
IL_004f: nop
IL_0050: ldloc.2
IL_0051: callvirt instance class [mscorlib]System.Collections.IEnumerator DuckTypingILCode.EnumerableCollection::GetEnumerator()
IL_0056: stloc.s CS$5$0000
IL_0058: br.s IL_0064
IL_005a: ldloc.s CS$5$0000
IL_005c: callvirt instance object [mscorlib]System.Collections.IEnumerator::get_Current()
IL_0061: stloc.3
IL_0062: nop
IL_0063: nop
IL_0064: ldloc.s CS$5$0000
IL_0066: callvirt instance bool [mscorlib]System.Collections.IEnumerator::MoveNext()
IL_006b: stloc.s CS$4$0001
IL_006d: ldloc.s CS$4$0001
IL_006f: brtrue.s IL_005a
IL_0071: leave.s IL_0090
} // end .try
IL_0073: ldloc.s CS$5$0000
IL_0075: isinst [mscorlib]System.IDisposable
IL_007a: stloc.s CS$0$0002
IL_007c: ldloc.s CS$0$0002
IL_007e: ldnull
IL_007f: ceq
IL_0081: stloc.s CS$4$0001
IL_0083: ldloc.s CS$4$0001
IL_0085: brtrue.s IL_008f
IL_0087: ldloc.s CS$0$0002
IL_0089: callvirt instance void [mscorlib]System.IDisposable::Dispose()
IL_008e: nop
IL_008f: endfinally
} // end handler
IL_0090: nop
IL_0091: ret
} // end of method ForEacher::DoForEach


Yes, it’s a bit ugly, but you will notice that other than naming, the code is just repeated twice. This is of course what we would expect, since the code should treat it the same regardless. All the foreach loop needed was to be able to get the object from the GetEnumerator method. Once it has that, it just uses the enumerator to do all of the work. This means that either class should work just as well.

This is the repeated line of code that shows up in two places to get the enumerator it will be using for its MoveNext() and GetCurrent() methods.

IL_0009:  callvirt   instance class [mscorlib]System.Collections.IEnumerator DuckTypingILCode.DuckCollection::GetEnumerator()
IL_0051: callvirt instance class [mscorlib]System.Collections.IEnumerator DuckTypingILCode.EnumerableCollection::GetEnumerator()


Now if you’re really paying attention, you will have looked at the Try-Finally block that is in the code to handle our IDisposables. That’s another neat thing happening behind the scenes, but that’s another blog post entirely.

If you would like to see another cool thing in the .NET Framework, you should check out what else you can do with Null Instance methods if you change those callvirts.

Ball Flow Recap: CodeMash Coding Dojo

CodingDojoFloorDecalsThe coding dojo at CodeMash 2012 was a blast this year. I ran two events in the dojo: a group exercise doing the Gilded Rose kata and the Ball Flow agile game. I thought the gilded rose kata we did as a group exercise was a great success. We had a good group of people, which was impressive considering that even with floor decals, people had trouble finding the coding dojo.

The coding dojo at codemash is a great place for actually doing things at CodeMash. If you’re tired of sitting there having someone talk at you, head to the coding dojo. It’s a place for writing code, learning, experimenting, and having a great time. We did katas, programming exercises, and some educational games in the dojo this year. If you did not make it to the dojo this year, we hope to see you next year!

Ball Flow

The Ball Flow game is an Agile exercise where a team of people work together in an experiment in self organization. The team will do some estimation, some planning, some retrospectives, and they will be trying to continually improve their process while aspects outside of their control continue to change. The team has to adapt and figure out how to keep working together effectively.

Object of the game:

Pass each of the 20 balls to each person in the group.

Rules of the game:

  • A person may touch a ball more than once, but doing so isn’t ideal.
  • Two people may not be touching the ball at the same time.
  • You may not pass the ball to your nearest two neighbors
  • If the ball touches walls (including floor and ceiling) or any furniture it must start over.
  • The person who first picks up the ball must be the last to touch the ball.

What this group did

Our group started out by figuring that if they created an oblong shape, they could pass across pretty easily. They got in this shape and began passing around. They had two tall people stand back a step so that they could launch the ball over everyone else across the group. Their final pass went behind the backs of one side of the group back to the starting person who removed the ball from the game.



They spent some time planning and adjusting between each iteration. They made sure not to make big changes fearing the catastrophe that could occur. Each time they made modest improvements to their time.


As the game went on we added challenges, in one round we added a large number of pens that needed to be passed around as well.

In the final round we added in bags of potato chips, which were harder to throw across the room. Each time the group still managed to make slight adjustments to accommodate these changes and still slightly improve their times.

The CodeMash 2012 Ball Flow team was awesome! Great job everyone!

Foreach, IEnumerable, IEnumerator, and Duck Typing

During my Software Craftsmanship Precompiler session, I heard one of the students say, “all you need is an IEnumerable to use a foreach loop”. This sparked a bit of fun when I asked Steve Smith, my co-presenter, if that was correct. He confirmed that it was, and I disagreed. Being the scientists that we are, we decided to try it and see what happened. I of course knew that duck typing in C# should allow the Foreach loop to compile without anything having the method required by the IEnumerable interface. This means that we just need a GetEnumerator method.

We wrote the code that did this and it compiled!

Duck typing is awesome, because it allows the language to treat my type the way I want it to because it has the right tools to do the job. The term duck typing comes from the idea that if it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.

In the foreach loop example, duck typing assumes that what you have here is able to be enumerated, because it has a method to get the enumerator. If we look at the IEnumerable interface, we can see that this is what we are required to implement.

public class MyCollection : IEnumerable
public IEnumerator GetEnumerator()
throw new NotImplementedException();

Now that we have our collection written and implementing IEnumerable, we can write a foreach loop that uses our collection.

var myCollection = new MyCollection();
foreach (var thing in myCollection)
// Do something with the thing

Finally, because of the duck typing in C#, we can remove the interface from the code, but keep the method.

public class MyCollection
public IEnumerator GetEnumerator()
throw new NotImplementedException();

It still compiles!

One of the many cool things about C# that I love. It’s a fun language, so go experimenting!

CodeMash 2012 Recap

Now that CodeMash is over, it’s about time that I deposited information about my experiences at CodeMash 2012 here.

This was my third time at this event that always offers great sessions, workshops, discussions, fun, and bacon.

I am honored to have again been given the chance to speak at CodeMash. I co-presented the Software Craftsmanship precompiler workshops with Steve Smith for the 3rd year running. This year, we broke our day-long workshop into 2 sections: one beginner session and one intermediate session.

Both sessions turned out really well. We had a lot of good verbal feedback from the attendees during the workshops, we had some of our morning people stick around for the afternoon, and I heard from other people that those who attended enjoyed the workshop.  I am really happy with how well it turned out. Thanks everyone who attended the sessions.

Beginning Software Craftsmanship

In the morning we did a beginner’s workshop that introduced the idea of Software Craftsmanship and what values go along with it. We discussed what people can do to get involved with their communities and realign their focus on building good, high quality software. As part of this, we show the group how they can work on improving their skills as Software Craftsmen through Katas and other programming exercises.

We had between 30 and 40 people attend the morning, beginner workshop, including a cobol programmer. We had the attendees mostly working on the Prime Factors Kata through the day. We started them doing the kata with little direction and asked that they do the work solo and without testing. We then had them do the kata again, but this time use testing to keep them on track designing their applications in a simpler way. In the third time doing the kata, we had everyone work in pairs on the kata to see how far they could get as a team using TDD.

Our main goal with the programming exercises in the morning is to have everyone leave with an understanding of pair programming, TDD, how to use programming exercises to hone their development skills, and we wanted them to leave motivated to work with their local communities to all become better at creating quality software. I believe we succeeded in our endeavor. The students talked about how the testing made the work easier and that pair programming was also much easier.

Intermediate Software Craftsmanship

The afternoon focused on some of the same ideas as the morning, but the people in the afternoon know about the values of software craftsmanship. We briefly reminded everyone, as I believe should be done. It’s important to remember and discuss why we do what we do. It gives us a chance to remember and reconsider everything we know and believe.

For this workshop, we had more than 50 people show up for the workshop, which meant that some people did not have table space for their laptops.

In the afternoon we did a few different exercises. One of them focusing on green-field development using good design patterns and practices to help reinforce how to use these effectively. The Greed kata is a great place to try out the strategy pattern as well as a few other good patterns. In the exercise, you continue to get more and more scoring rules added. Eventually, you want to get to following the Open/Closed Principle so that you’re not changing the existing code each time.

The other exercise we did is one which starts out with existing code to refactor. In the refactoring exercise we ask you to add a new feature. It then becomes your choice how to do it. You could just hack in an “if” statement. You could also take some time and refactor. Before you refactor, however, it’s usually a good idea to try to get some tests in place. To make things even more like real code, you need to perform a couple of careful refactorings before you can put your first tests in place. You also get to decide how many tests you want to write and how much to refactor when adding this new feature.

Future Events

If you want to take part in this or a future workshop, I am hoping that CodeMash will invite me back next year to do another great workshop or two. I am also hoping to do a free Software Engineering 101 event again in Cleveland.

Overusing Interfaces and Injection

In software development, it is very important to continually learn and experiment with new techniques for building great software. Our job is to learn and improve the quality of code that we build over time. It is through this progression of experimentation, failing, succeeding, observing, reading, listening, and teaching that we as developers improve. In this post, I am going to discuss one way in which we as developers have learned something great and have taken it to the point of failure. This will allow us to learn, resolve, create new techniques, and succeed in the future.

What is Dependency Inversion?

One of the most important SOLID principles for testing our applications is the Dependency Inversion principle. I am very glad to see many more codebases using this technique as time goes on, however, I am seeing nearly as many others getting caught up in an easy mistake of using too much injection and putting interfaces on everything regardless of necessity. Lets start by defining dependency inversion so we’re all on the same page.

From Wikipedia:

In object-oriented programming, the dependency inversion principle refers to a specific form of decoupling where conventional dependency relationships established from high-level, policy-setting modules to low-level, dependency modules are inverted (i.e. reversed) for the purpose of rendering high-level modules independent of the low-level module implementation details. The principle states:

A. High-level modules should not depend on low-level modules. Both should depend on abstractions.
B. Abstractions should not depend upon details. Details should depend upon abstractions.

Reading directly from this, we can see that it says we should be depending on abstractions and in doing so we take a much lighter dependency. A dependency on an abstraction is not a big deal. A dependency on a concrete class is a big deal.

Is what I just said always true? No, it depends on the abstraction and the concrete class. For example, I make an exception for simple classes provided through the framework or language my code is primarily based on. For instance, I have no problem saying that my method depends on being given a DateTime object since there is no real gain by abstracting that object since that is a part of the framework and I will always be injecting in an object of that type.

When are interfaces and injection being overused?

One example of over-architected injection that I see a lot comes from something that I’ve taught many times when explaining SOLID. It’s the classic example of a dependency that people don’t realize they have.


I assume most of my readers know that this is a dependency taken directly on the system clock. It’s important to inject this dependency when your code behaves differently based on the value returned from that static method. When we extract that dependency, people have been taught (by many people including me) that a good way of testing this is to have some kind of IClock interface with an implementation of SystemClock accessing the computers clock by calling that static method we were just discussing.

Now when we write our method, we just give it a parameter of IClock. When we run our code in production, it’s taking in the SystemClock object, and in our tests we’re using a mock object. Great! We’ve reversed the dependency! Is that really what we wanted though? It might have been, but in some cases we could have just passed in the DateTime instance object returned from that method. This would have reduced complexity in our code.

Because we used this interface instead of just depending on simple concrete classes, we’ve actually made our code more difficult to use and maintain. Isn’t that the whole reason we were following SOLID in the first place? Yes, yes it is. This is of course a simple example, but you can find larger examples of where you could test your code and build in a nice structure without having to create pointless interfaces. Heck even in this example, you might have a good reason to need that Interface, but I am sure that you could get away with using it less. Every time you add that layer, you add complexity. Sometimes adding it is OK, because it gives you a much needed seam, but I doubt you need it as often as you think.

Please make sure that you need the interfaces and layers of abstraction before creating them. I’ve come across many codebases that become as complex or more simply by trying to do things “the right way”.

The road to software development hell is paved with good intentions.


Don’t like the way I phrased something? Think I overgeneralized? Did I make a mistake?

Call me out on it!

I appreciate the feedback.

Types of ASP.NET MVC 3 Action Results

This will surprise some of you that know me or the company I work for, but not all of our staff are experts with ASP.NET MVC. In fact, I am hoping that the couple who aren’t will read this post and learn a little bit more about the topic.

Since the actions of controllers in MVC are dealt with constantly, I think it is a good place to start. This post is going to briefly describe the different types of results that are available to you in ASP.NET MVC 3. I will show some of the code that makes them work, which should make all of this seem a lot less complicated.

When creating new controllers in ASP.NET MVC 3, they will come with one or more actions by default. This depends on whether you selected a template which includes extras for you. The Empty controller template comes with an Index action with a return value of type ActionResult.


The action result is a very generic return value for an action. This is because it is the abstract base class for other types of actions. It is actually a very simple class having only one method that needs implementing.

public abstract class ActionResult
public abstract void
ExecuteResult(ControllerContext context);

Inheriting from the ActionResult are the following classes:

  • ContentResult
  • EmptyResult
  • FileResult
  • HttpStatusCodeResult
  • JavaScriptResult
  • RedirectResult
  • RedirectToRouteResult
  • ViewResultBase

These are the classes that inherit from ActionResult indirectly:

  • FileContentResult
  • FilePathResult
  • FileStreamResult
  • HttpNotFoundResult
  • HttpUnauthorizedResult
  • PartialViewResult
  • ViewResult

ViewResultBase, ViewResult, and PartialViewResult

The ViewResult is the most common concrete type you will be returning as a controller action. It has an abstract base class called ViewResultBase, which it shares with PartialViewResult.

It is in the ViewResultBase abstract base class that we get access to all of our familiar data objects like: TempData, ViewData, and ViewBag.

PartialViews are not common as action results. PartialViews are not the primary thing being displayed to the user, that is the View. The partial view is usually a widget or something else on the page. It’s usually not the primary content the user sees.

This is the common return syntax, and it means that you’re returning a ViewResult.

return View();

That is actually a call to the base Controller.View method, which is just going to call through with some defaults.

protected internal ViewResult View()
return View(null, null, null);


The beauty of ASP.NET MVC is actually in its simplicity though, because all that really did was create our ViewResult for us. If we take a look at the method that is being called you can see that we’re just taking a little shortcut and keeping our action clean of this code we would otherwise repeat every time we wanted a ViewResult.

protected internal virtual ViewResult View(
string viewName, string masterName, object model)
if (model != null)
ViewData.Model = model;

return new ViewResult
ViewName = viewName,
MasterName = masterName,
ViewData = ViewData,
TempData = TempData

Notice how simple that really is. All it did was put the model data in if we specified it, give the ViewResult the Controller properties that we set already, and assign the viewName and masterName.

Keep in mind, that we already saw that the abstract method in the ActionResult was the ExecuteResult method. The last two things to look at with the ViewResultBase are the ExecuteResult method and its abstract method FindView, which is being implemented by ViewResult and PartialViewResult.

public override void ExecuteResult(
ControllerContext context)
if (context == null)
throw new ArgumentNullException("context");
if (String.IsNullOrEmpty(ViewName))
ViewName = context.RouteData

ViewEngineResult result = null;

if (View == null)
result = FindView(context);
View = result.View;

TextWriter writer = context.HttpContext.Response.Output;
ViewContext viewContext = new ViewContext(
context, View, ViewData, TempData, writer);
View.Render(viewContext, writer);

if (result != null)
result.ViewEngine.ReleaseView(context, View);

This method is also not very complicated. It checks to make sure we have context, and then if we don’t have the ViewName then we get that information from the RouteData. Remember in MVC that the name of action is included in the RouteData, so we can use that as the default view name. This means that in the Index action, if we just call View(), it will give us a ViewName of “Index”.

We then get the view we’re looking for by calling the FindView abstract method, which means we’re calling through to either ViewResult and PartialViewResult. Those I am not going to get into the guts of, but each one is going to try to find the correct view based on the name using its collection of ViewEngines.

Once we have the view, we are able to tell it to render itself using the context and the TextWriter we give to it.

That’s all there is to a ViewResult.


The content result lets you define whatever content you wish to return. You can specify the content type, the encoding, and the content. This gives you control to have the system give whatever response you want. This is a good result to use when you need a lot of control over what you’re returning and it’s not one of the standards.

Its ExecuteResult override is extremely simple.

public override void ExecuteResult(ControllerContext context) 
if (context == null)
throw new ArgumentNullException("context");

HttpResponseBase response = context.HttpContext.Response;

if (!String.IsNullOrEmpty(ContentType))
response.ContentType = ContentType;
if (ContentEncoding != null)
response.ContentEncoding = ContentEncoding;
if (Content != null)

It just puts what you specified directly into the response.


There is no simpler result than the EmptyResult. All it does is override the ExecuteResult method and since that method is void, the method is empty.

I really don’t think I need that code snippet for this one.

FileResult, FileStreamResult, FilePathResult, and FileContentResult

If you want specific actions to send files as the response, then the FileResult is for you. Sadly, the FileResult is abstract, so you’ll need to use one of the inheriting classes instead. Each of these actually just overrides the WriteFile method for the abstract FileResult class.

If you want to just send the contents of the file back with the array of bytes for the file, then you want the FileContentResult. It uses the response’s OutputStream and writes those bytes directly into the stream sending it down to the user.

If you want to transmit the file using its name, you can use FilePathResult, which will call through a whole bunch of layers finally down to the HttpResponse. Once there it is going to create a new FileStream for your file and write the stream to the response allowing the file to be accessed from your action.

If you’ve already got a stream you can use the FileStreamResult, which will read all of the data from your stream and then write it into the OutputStream to be send back in the response.

These really aren’t all that complicated, but if you want to have control over the file downloads in your application, this is a great way to do it. These give you the power to put any code you want in your action before you give back the FileResult.


The HttpStatusCodeResult is as simple as the ContentResult. In fact, the two are quite similar since they both just directly modify the response object.

This one lets you return any StatusCode you want and you can include a StatusDescription for specifics.

public override void ExecuteResult(ControllerContext context)
if (context == null)
throw new ArgumentNullException("context");

context.HttpContext.Response.StatusCode = StatusCode;
if (StatusDescription != null)
.StatusDescription = StatusDescription;

See how simple that is? It’s basically just two lines of code with some null checking included.

HttpNotFoundResult and HttpUnauthorizedResult

These two results are actually just implementing the HttpStatusCodeResult, which means that they are very simple and just set the StatusCode to 404 for the HttpNotFoundResult and 401 for the HttpUnauthorizedResult.


About as simple as plenty of the others, this is just a quick way of getting JavaScript returned from a action. It’s similar to the ContentResult, but it has the ContentType hardcoded to “application/x-javascript” and just writes out the Script property.

public override void ExecuteResult(ControllerContext context)
if (context == null)
throw new ArgumentNullException("context");

HttpResponseBase response = context.HttpContext.Response;
response.ContentType = "application/x-javascript";

if (Script != null)


This one is a bit more complex, but still not very. It also has hardcoded its ContentType, but what makes it a bit more complex is that it uses a hardcoded JavaScriptSerializer to serialize the JSON data before writing it directly to the response.

public override void ExecuteResult(ControllerContext context)
if (context == null)
throw new ArgumentNullException("context");
if (JsonRequestBehavior == JsonRequestBehavior.DenyGet &&
"GET", StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(

HttpResponseBase response = context.HttpContext.Response;

if (!String.IsNullOrEmpty(ContentType)) {
response.ContentType = ContentType;
else {
response.ContentType = "application/json";
if (ContentEncoding != null) {
response.ContentEncoding = ContentEncoding;
if (Data != null) {
JavaScriptSerializer serializer =
new JavaScriptSerializer();

RedirectResult and RedirectToRouteResult

These to are a little bit more complex, but both are ways of redirecting. Each one can either be a permanent or temporary redirect and they both just use the Redirect methods on the Response object.

For redirecting to a route, it is going to generate a URL to the route using the UrlHelper’s GenerateUrl method. For the RedirectResult it is instead going to use the UrlHelpers GenerateContentUrl method.

Either of these two are useful, and both will maintain your TempData if you need to pass something along with the redirect, all you have to do is put it in TempData.


I hope you’ve learned that the results of actions in MVC are not actually very complicated, but there is a lot you can do with them. You’re not being forced into just displaying views. You have a lot more control than that. None of them were that complicated were they? The code under the hood is not always complicated, so it’s worth taking a look from time to time. If you examine how something is working, it’s often far easier to use it.