Autogenerating C# classes? Add the “partial” keyword

I’m not a big fan of code generation, but I recently thought up a scenario of making it a little more manageable. Here’s the scenario, let’s say you’ve got some tool that generates a lot of C# code for you. Perhaps it’s a “clever” db-to-CRUD code translator. They exist out there. You can’t really change those classes, as your changes can be over-written by whatever tool is generating the code.

Using those types hard-code a database dependency into your domain classes, so you can’t really test in automation anymore.

Two strategies for working with this problem.

1. The usual wrap+fake maneuver. You can encapsulate the auto-generated class into some abstraction (interface or abstract class) and have your domain objects couple to that wrapper.

2. Change the tool to add the “partial” keyword to the class (or change the output of the tool, realizing that you may have to change it again when it gets over written, but it’s what, seven characters?)

Now that this auto-generated type is partial, you can extend it without changing the file. It’s open-closed at the file level. The original example I had was to add just the following in a distinct file.

public partial class AutoGeneratedType: SomeInterface{}

public interface SomeInterface

Now you can use ReSharper’s “pull Member up” automated refactoring to build the abstraction, couple your domain objects to the interface, and make fake versions for testing in isolation. You are using ReSharper, aren’t you?

And, of course, just like any time that you break a concrete type dependency, you can do things like substitute a different version, add a proxy, etc.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: