I like reading code. Let it be doing code review, exploring 3rd parties, or just reading the reference source. You can learn so much from others. Those aha! moments are the best. In this blog post, I want to introduce you a neat trick, that I learned from a coworker. It involves the using(…) statement and the IDisposable interface.

Using temporary directories

Temporary directories are useful, when it comes to importing data, making a copy of data or just providing throwaway storage. Take a look at the TemporaryDirectory class, which abstracts the notion of temporary directory into a type.

Highlights:

Check the constructor. A _real_ directory will be created when an instance of the class is created. It’s not a pig in a poke. The directory is accessible via the Path property. The temporary directory implements the IDisposable interface, which gives a hint to the caller that it’s not a permanent directory. It has a lifespan and the object’s owner can control it. All by the power of C#.

Using the temporary directory abstraction

Let’s put on a show and see how the TemporaryDirectory can be used. Let’s add an ApplicationStorage factory/manager class first as I want to create an even more powerful abstraction. The gains would be:

The caller doesn’t have to be worried where the temp directory is created.

The ApplicationStorage could provide a mechanism, which would delete directories every now and then, if the Dipose() method would fail for some reason.

The moment of truth:

The cake is a lie

What I really like is that the operation, which involves the usage of a temporary directory, is scoped. Once the business is done, everything is cleaned up. The temporary directory is gone. As there are different layers of responsibilities, it makes the design more decoupled. The layers of the cake we baked:

Creating and deleting the directory

Defining where the temporary directories should reside

The actual work being done

Extra: application wide cleanup as a fallback

Readability matters

By taking advantage of the using statement, we also made our code more readable and expressive. Nonetheless, you could implement it without all the fluff, however, it’s more code in the long run and hard on the eye and I wouldn’t be surprised if the code got copy pasted all over the code base in this form.

Conclusions

If you use the right LEGO parts together there’s a chance that you end up with readable and reusable code. In this post, the LEGO parts are the using statement and the IDisposable interface. Sometimes it’s not obvious how different pieces can be used for building powerful abstractions. That’s why I like reading code.

This was the first part of a blog post series. Next time I will bring another example of the using+IDisposable combo. Stay tuned.

Checkout the full source code. Questions? Comments? Concerns?