Lazy initialization

My experience working my way through the Clean Code book and videos has gotten me interested in refactoring some of my old code. I have a large API project that I maintain at work, and it’s gotten a little out of hand over the last few years. In particular, there’s one class that got so large that I broke it up into multiple partial class files some time ago. Overall, it would have been around 5000 lines of code if I hadn’t broken it up. Of course, partial class files don’t really change anything; it’s still one big class, technically.

So I started looking for ways to break it down into actual separate classes. What I wound up doing was to leave stuff that was needed across all the code in the old class, then moving all the specific stuff from the partial classes into new “child” classes. I created a new base class for these child classes, then added code to the original (now “parent”) class to contain all of the children as singletons, instantiated as needed.

The code to do that looked a lot like the code in this Stack Overflow question. That was fine, but once I got all that done and working, I started looking around for ways to streamline or simplify the declarations. I tried out a few things, and decided on using the Lazy<T> class. I’m sure I must have stumbled across it before, but I’d forgotten about it and had never actually used it. It took me a little while to figure out exactly how I should use it, in my particular use case. I don’t have anything super-interesting to say about that, but I thought I’d just post a few links that I found helpful:

Overall, I think the code is a little better for having been refactored this way, though I’m still not quite satisfied that I’ve cleaned things up as much as I should.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.