# Friday, November 28, 2008

We all love unit tests (do we?). Yes we do (repeat 100 times). And we all love mocking for making life easier, but sometimes we just want to write some simple unit tests that don't require any mocking at all, because the code you are testing is easy to test without having to resort to all those mocking tricks

But what if you need to test code that relies on the date or some elapsed time? Let's say you wrote a simple caching class that automatically removes items from the cache when a certain amount of time has passed since the last access. It's tempting to slap some Thread.Sleep() calls in there to trigger expiration of cache items, but that will slow down your unit test, and most importantly, it's not accurate. What if you want to test some edge cases? Like, what happens when you access an item at the exact timeout period?

A few years ago I worked with a brilliant Java architect who simply said: "just mock the time!". What he meant was that I should create a fake DateTime class which behaves like the real DateTime class with one important difference: YOU control the time, not the system clock.

How is that done?

Simply create an interface with a single getter property of type DateTime:

public interface ITimeProvider 
{
   DateTime Now { get; }
}

Then you create 2 classes that implement this interface: one that returns the real time, and one that can be used to control a "fake" time:

public class RealTimeProvider : ITimeProvider
{
    public DateTime Now { get { return DateTime.Now; } }
}

public class MockTimeProvider : ITimeProvider
{
    private DateTime _time;

    public DateTime Now { get { return _time; } set { _time = value; } }
}

Of course the class(es) you want to test should be aware of this. For example, our cache class could look like this:

public class Cache
{
     private ITimeProvider _time = new RealTimeProvider();

     public ITimeProvider TimeProvider { get { return _time; } set { _time = value; } }

     // ... the rest of the class implementation
}

In our class implementation, all calls to DateTime.Now should be replaced by TimeProvider.Now.

And now the fun part, faking the time in our unit tests:

[Test]
public void TestCacheTimeout()
{
    ITimeProvider time = new MockTimeProvider();
    Cache cache = new Cache();

    cache.TimeProvider = time; // Tell our cache class to use our fake time

    cache.Add("A" , 1); // add an item to the cache

    Assert.IsTrue(cache.Contains("A")); // check if it's added

    time.Now += TimeSpan.FromHours(1); // let one hour go by...

    Assert.IsFalse(cache.Contains("A")); // check if it was automatically removed
}

That's pretty cool and simple, isn't it? Wouldn't it be nice if we could do the same in real life? ;-)

Next week I'll talk a little about unit testing multithreaded concurrency issues...

kick it on DotNetKicks.com
Friday, November 28, 2008 6:41:29 PM (W. Europe Standard Time, UTC+01:00)  #    Comments [0] -
 |  |  | 
# Monday, August 20, 2007

What's worse than:

  • Global variables?
  • Badly chosen variable names?
  • ASP.NET WebForms :)?
  • Leaky abstractions?
  • ... enter your worst coding nightmare ...

I've got one word for you:

Dependency Injection (well, that's two words actually)

Why?

Remember 20 years ago? All of a sudden, WYSIWYG word processors were all the rage. For a good reason. WHAT YOU SEE IS WHAT YOU GET. Exactly!. Writing, editing, reading a document while you don't have to worry about what the end result will look like. It was heaven.

The same is true for writing and reading code. Code should (more or less) do what it looks like it is doing. That's obvious.

What does Dependency Injection do with your code? Nobody but the guy who implemented it knows. Now, THAT's comforting.

You read a piece of code, and you think you understand what it's doing, but the actual code is something completely different at runtime. WYSINWYG. A maintenace nightmare.

I know a lot of people will disagree, but all this code-changing magic is an accident waiting to happen. I wonder if this stuff is used in the Space Shuttle program code.

But that's just MHO.

kick it on DotNetKicks.com
Monday, August 20, 2007 7:56:47 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [4] -
 | 
# Monday, August 06, 2007

One of the most powerful features in .NET is the ability to use reflection to do all kinds of neat stuff at runtime, like

  • Find out what properties, fields, methods, etc. are in a class
  • Create objects without knowing their type at compile time
  • Call methods by name (even private ones)
  • Check attributes on classes, methods, fields, …

The web framework I built over the last few years, ProMesh.NET, relies on reflection for a lot of the features it offers. Often though, I am asked if the heave use of reflection doesn’t have a significant impact on performance.

My answer usually is: YES, but it doesn’t matter. Now you probably think that I don’t care about performance or that I’ve had too much too drink. None of the above. I’ll explain:

In ProMesh.NET, there’s a feature that allows you to just declare session properties in your class that will be constructed at runtime, like this:

   private SessionProperty<string> _mySessionVar1;
or
   private SessionProperty<string> _mySessionVar2 = new SessionProperty<string>();

You don’t have to initialize _mySessionVar1. The framework uses reflection to construct the object.

Creating _mySessionVar1 is about 20 times slower than creating _mySessionVar2. Shocking? Yes. Unacceptable? No!

The reason why it is not unacceptable is that it takes 2.2 µs (microseconds) to create _mySessionVar1, and 0.12 µs (microseconds) to create _mySessionVar2. These figures include dynamically iterating the over the class members, determining their type and looking up the appropriate constructor. This is the simplified code which creates the fields at runtime:

foreach (MemberInfo member in GetType().GetMembers())
{
if (member is FieldInfo)
{
FieldInfo field = (FieldInfo) member;

ConstructorInfo constructor =
field.FieldType.GetConstructor(Type.EmptyTypes);

field.SetValue(this, constructor.Invoke(new object[0]));
}
}

Considering this happens when a web page is requested, which usually involves some database access, a little disk access and some other time-consuming stuff, a complete web page request takes between 50ms and 2000ms. Assuming we have 20 session variables to construct at runtime, the overhead is … between 0.08% (worst case) and 0.002%.

So, yes it is MUCH slower, but it doesn’t matter. (not for applications of this kind)

kick it on DotNetKicks.com
Monday, August 06, 2007 8:48:01 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [3] -
 |  |  |  |  | 
# Wednesday, July 25, 2007

Yesterday, an old article resurfaced on dotnetkicks.com about validating Guid strings. Several comments hinted at the possibility of letting the .NET Framework convert it to a Guid and catching the FormatException.

WTF !?

I must be very old-fashioned, because I am still very religious about (mis)using exceptions in normal application flow. Exceptions were designed for exceptional events, not for validating user input.

Even Microsoft picked up on that, because they added a bunch of TryParse() methods in version 2.0 of the .NET Framework.

In case you’re wondering if there are any REAL reasons for avoiding exceptions in the normal flow of an application, I’ll give you two:

  1. Exceptions are slow. Let me repeat: SLOW.
  2. When you are in a debugging sessions, and you told the debugger to break at the first exception (which is often done), you will know what I’m talking about.

 

kick it on DotNetKicks.com
Wednesday, July 25, 2007 8:31:38 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [0] -
 |  | 
# Saturday, July 21, 2007

In the early days of web development, it was common procedure to write application logic inside your HTML pages using ASP, JSP, PHP, Perl or another early web application development framework.

Of course, back then we didn’t know any better, but don’t you just cringe when you see something like this:

<table border="1">
<%
For I = iRecFirst To iRecLast
	Response.Write "<tr>" & vbCrLf
	
	For J = iFieldFirst To iFieldLast
		Response.Write vbTab & "<td>" & arrDBData(J, I) & "</td>" & vbCrLf
	Next	
	Response.Write "</tr>" & vbCrLf
Next ' I
%>
</table>

I know, this looks pretty simple, and the learning curve to write applications in this way is not that steep, but maintaining something like this is a nightmare.

Microsoft saw the need for something better and came up with ASP.NET. Indeed, at first glance it was a big improvement, urging developers to cleanly separate code from markup by providing the "code behind" way of programming. But if you look closer it was still a mess. Let me tell you why:

  • There’s a (very limiting) 1–1 relationship between the view and the code. Every .ASPX has one code behind file, and one code behind file has one .ASPX file. Implementing the MVC pattern is impossible without resorting to a bag full of tricks.
  • Events are wired in the markup, so the markup is controlling the application, not the other way around
  • The .aspx files are "kind-of" HTML files, but when you try to edit them in a standard HTML editor (Dreamweaver for example), you're in for a (nasty) surprise. ASP.NET tags are not recognized correctly, let alone rendered. So you are pushed into using the Microsoft ASP.NET markup editor, which is the crappiest piece of junk ever built.
  • Properties influencing the behavior of user interface elements are defined in the markup. And the other way around: properties defining the look of your application sometimes have to be defined in code
  • Standards based HTML/CSS? What standards based HTML/CSS?

To this day, Microsoft is still holding on to this broken development model for web applications. The Java guys had more inspiration in that area: Struts, Tapestry, Wicket, SiteMesh, Spring, ... Good ideas that quickly turned into Enterprise Frameworks that were too intimidating for the average developer (isn't this a pattern for all Java-based technologies?)

Light at the end of the tunnel?

Maybe... Ruby On Rails, MonoRail, DotNetNuke, Spring.NET,... Cool stuff, VERY cool stuff.

Which brings me to the point of this article. While I didn't have time to look at all these frameworks, I am still a little annoyed by the lack of separation between the actual presentation (markup) and the code controlling the presentation. The other day I was checking out MonoRail and was browsing through the samples, and I saw a lot of ASP-like stuff in the HTML markup. Loops, method calls, the whole shebang. I felt thrown back to the nineties.

Maybe I am too religious about this, but I like to see a 100% separation between code and markup (presentation). My requirements for a web application framework are pretty clear:

  • Pure HTML files should be used. By pure HTML, I mean that you should be able to give the HTML files to a web designer and let him/her make changes without having to worry too much about these funky codes that these weird developers have put in.
  • No hints of any application logic or code in the presentation markup
  • The learning curve should be gentle, without losing flexibility and performance
  • MVC has to be easy to implement (or included in the framework), without forcing developers to use it. 90% of web developers don’t use MVC, so don’t force them to use it if they feel more comfortable developing in other ways
  • Easy Ajax integration (I am not talking about black box toys like Microsoft Ajax)
  • Performance! Performance! Performance!

In a few days, ProMesh.NET, the web application framework I have been building, using and improving for the last 4 years will be published as Open Source on CodePlex. It’s a lightweight , fast web application framework that satisfies the requirements listed above and I look forward to sharing it with the .NET community.

kick it on DotNetKicks.com
Saturday, July 21, 2007 11:26:31 PM (W. Europe Daylight Time, UTC+02:00)  #    Comments [6] -
 |  |  |