Archive for October, 2009

My Top 10 Personal Favorite And Overlooked Posts

2 commentsWritten on October 29th, 2009 by
Categories: About The Blog

I apologize for just another link dumping of my own posts yet again, but i have some posts that are personal favorites of mine but that didn't quite get the attention that i thought they deserved. Instead of thinking that they suck (which they very well might) i tend to tell myself that these unfortunate posts were merely overlooked ;)

  1. The Life And Times Of A Bug

    This is definitely my nr 1 favorite post. I guess it was a bit too far out there for most people but you have to admit at least one thing: you've never read anything like that before :p

  2. Ethics In Software Development: Pragmatism Over Dogmatism

    Dogmatism of any kind is wrong. Pragmatism isn't always ideal either, but a healthy balance between them is a necessity in this business.

  3. Buzzword Driven Development Isn’t Gonna Help You

    I hate it when people go overboard with buzzwords, and it shows in this post.

  4. Make It Work, Make It Clean?

    I really loved this post... it's about an approach that one of my friends used (and still uses from time to time). I certainly don't recommend this approach to anyone because i can only imagine a handful of people pulling this off successfully, but it's interesting nonetheless.

  5. Test Doubles: When To (Not) Use Them

    I actually think this is pretty good advice about when to use test doubles, and when not to. Unfortunately, hardly anyone read it :)

  6. Which Path To Follow?

    Which path should one follow if one is merely looking to improve continuously?

  7. Thoughts on code reviews

    Discusses a different approach i once took for a code review.

  8. Is SQL going the way of Disco?

    People are writing less and less SQL... my question was: why should they?

  9. Are women better developers than men?

    If the majority of male developers sucks, is it a stretch to think that maybe women on average would be better at it than we are?

  10. Programming Languages Don’t Matter

    They really, really don't.

Hopefully some of you will like a few of these posts now :)

Stop Exposing Collections Already!

20 commentsWritten on October 28th, 2009 by
Categories: Code Quality

Every time i see code with properties that return List<T>, IList<T>, ICollection<T> or any other of the types which allow you to modify the contents of a collection, i cringe a little. In most cases, the only reason to expose the contents of the collection is for read-only usage. You want people to be able to use the objects in the collection, but why on earth do so many developers continuously enable someone else to modify the internal state of the collection that they are holding?

The problem that i have with exposing a collection's values through a type which enables other pieces of code to modify the state of that collection is that it is effectively a pretty big breach of encapsulation. You no longer have sole control over the contents of the collection. Anyone can effectively add and remove elements from the collection, or even clear them entirely, without your object knowing about it. Obviously, this can cause subtle side-effects in the behavior of your object. Which can (and sooner or later will) lead to some quality time between you and your debugger. You also no longer have the ability to easily change the type of collection you're using which might prevent certain future improvements that you can make to a class. And in case you're wondering why you'd want to change the type of collection, check out an example where the benefit was huge.

In a lot of cases, people do this because they don't know any better or because it's the easiest thing to do. I can't tell you how many times i've seen people expose List<T> simply so that some calling code could use the ForEach method of that list. How long does it take to write a ForEach extension method for IEnumerable<T>? Granted, it should've been included in the .NET framework already but just because it's not doesn't mean you can't do so.

Here's my philosophy on exposing collections: if i'm writing a class that is responsible for holding a collection, i take away every ability to directly modify the contents of the collection. I typically expose the collection through an IEnumerable<T> property, and if necessary i will provide a specific AddXxx and RemoveXxx method. That's it. You can do every single thing you need to do with the collection through IEnumerable<T>'s extension methods and through the AddXxx and RemoveXxx methods that i provide. Meanwhile, i have every ability to choose the collection type that i want to use, or to modify it later on. Furthermore, i can eliminate the possibility of side-effects in my code due to unexpected externally caused mutations in the state of the collection.

The only situation in which i think it's OK to return a real collection type is if you have a method which is responsible for creating a list, but is not supposed to hold on to it. In that case, the created collection is clearly intended to be used in whatever way makes sense by the consumer. After all, you created the collection specifically for the consumer so they can do whatever they want with it. But if you need to hold a reference to the collection for some reason, then you probably also have more responsibilities than merely creating the collection. In that case, the collection is yours and you should encapsulate it as such.

Prefixing Instance Fields?

17 commentsWritten on October 26th, 2009 by
Categories: Code Quality

I was talking to a friend the other day about prefixing instance fields. His opinion was that by prefixing instance field names (with an underscore for example) you have the benefit of immediately showing the difference in scope between the usages of a local variable in a method, or the usage of an instance field.

There is indeed a legitimate possible problem here: any possible mutation of an instance field in a method can have an intended or unintended impact somewhere else in the class since the mutation will outlive the duration of the method call. So it is important to be aware of this and that you are entirely sure that any possible mutation is actually intended and that no unintended mutations will occur because of some faulty code in a method. I don't however think that prefixing field names is the best solution to avoid this problem. There are two practices that i recommend to easily avoid unintended mutations of fields in methods.

The first is to use as few fields as possible. To avoid any misunderstandings: i'm not saying that you shouldn't use fields! I'm just saying that fields need to justify their existence. Fields inherently make up the state of an object, so if you don't need a particular piece of data to hang around longer than say, the duration of a method call, then don't put that data in a field. If you need to access that data in another method that will be called from the originally called method you can simply pass it to the other method with a method parameter. If you notice that you're frequently passing the same pieces of data to a couple of methods, then you probably need to introduce a parameter object. Simply put: do not use fields unless the data you want to store in them are an inherent part of the object and the data needs to hang around for a while.

The second practice is too keep your methods short and focused. If you're working with large methods, then i can certainly understand why you would want all the help you can get to easily spot mutations of fields. There's only one question: why are you working with large methods? There are truly very few legitimate reasons for not splitting up large methods into separate reusable methods. When you use many small methods instead of large methods, it's much easier to keep your focus on what any particular piece of code is supposed to do, and what it's really doing. And if your methods are short, you will very easily see when a field is being used instead of a local variable.

The combination of these two approaches leads to a lot less unintended mutations of fields. And as a bonus, you get a lot more readable and maintainable code as well. If however you still like to get some visual help in identifying field usage in methods, you can enable the Color Identifiers feature in Resharper (available in the Options window under Code Inspection - Settings - Color identifiers) which will result in fields being represented with a different color from regular variables.

What do you think about this? Do you still prefer to prefix field names, and if so, why?

Finally Some Real Improvements For Automated Testing In .NET

5 commentsWritten on October 25th, 2009 by
Categories: testing

As most of you already know, i'm a proponent of unit testing and automated tests in general. There is however one inherent flaw that comes with the unit testing approach: if you didn't think of a problem, you didn't write a test for it, and thus, you're not protected from that problem.

In the past two years we've seen the .NET world gradually accept the concept of TDD, and it has been extended somewhat with the whole BDD thing. However, there hasn't been a single fundamental change which allows you to take away that inherent flaw. Every single variation that has been introduced in the TDD/BDD world is honestly very minor (dare i even say pointless?) because it all boils down to different syntax and slightly different ways of organizing your test fixtures. But again, even if you are doing the very latest flavor of the month when it comes to automated tests, you're still not protected from problems that you didn't think of.

Mark Meyers, a former coworker of mine, has been working hard on porting QuickCheck to .NET and the result is the QuickNet project. Instead of being yet another minor evolutionary step in the automated testing world for .NET, you could actually consider this to be a revolutionary improvement. For the .NET world that is, since other developer communities have adopted this new approach already some time ago.

I highly encourage you to check out what QuickNet is about. I'm about to get much more involved with the project, from a development point of view as well as using it and trying to spread the good word. This is something that actually can offer you substantial benefits over classical unit testing approaches so you really would be doing yourself a huge favor in giving this a shot. Keep in mind that it's still pretty early and that the codebase is still going through some major changes. There is no official release yet, so breaking changes can (and probably will) occur if you already try it out.

There also isn't any official documentation yet either, but Mark has some great posts about QuickNet's usage and there's also a couple of nice examples in the code already. In fact, we also have a few QuickNet tests to test... well... QuickNet itself. Head on over to some or all of the links i put in this post, and start learning :)

Testability Of Date-Dependent Code

16 commentsWritten on October 21st, 2009 by
Categories: testing

Just read a post by Jonathan Oliver where he talks about a solution he saw to tackle the problem of date-dependent code in tests. As you probably know, code that uses the current date can very easily cause testability problems. Code that accesses DateTime.Now or DateTime.UctNow can quite easily cause tests to fail for no valid reason when the tests happen to run on a certain date, on weekend days, at the end of the month, etc...

The problem obviously is that you can't override the value that DateTime.Now will return during your tests. Many people seem to resort to using some kind of DateTimeService dependency which each piece of code that needs the current date will use. Basically, something like this:

    public interface IDateTimeService
    {
        DateTime Now { get; }
    }

The implementation that will be used at runtime then looks like this:

    public class DateTimeService : IDateTimeService
    {
        public DateTime Now
        {
            get { return DateTime.Now; }
        }
    }

Code that needs the current date simply declares a dependency on IDateTimeService and at run-time the IOC container will inject an instance of DateTimeService to fulfill the IDateTimeService dependency. At test-time, the IDateTimeService is mocked so you can easily set which date should be returned for each test.

Personally, i'm not a fan of this approach. I mean, i use the same approach for most dependencies but for simply getting the current date this is a bit too much IMO.

Instead, we simply use something like this:

    public static class DateTimeProvider
    {
        private static DateTime? dateTimeToReturn;
 
        public static DateTime Now
        {
            get { return dateTimeToReturn == null ? DateTime.Now : dateTimeToReturn.Value; }
        }
 
        public static void SetDateTimeToReturn(DateTime overriddenCurrentDateTime)
        {
            dateTimeToReturn = overriddenCurrentDateTime;
        }
 
        public static void ResetCurrentDateTime()
        {
            dateTimeToReturn = null;
        }
    }

And our real code simply calls DateTimeProvider.Now instead of DateTime.Now. In our tests, we call the SetDateTimeToReturn method to provide the date that we want to use for a particular test. At the end of the test, simply call the ResetCurrentDateTime method and that's it.

I generally don't like static methods but in this case, this is a very simple solution to this specific problem. And you know how the saying goes: "do the simplest thing that could possibly work". And as long as that works, resist the urge to change it.