Wednesday, June 4, 2008

Replace strings for property names with type-safe version

At times you have the misfortune of having to write property/field (I’ll just call it properties from now on) names as strings, for instance in advanced NHibernate queries. (In general, NHibernate Query Generator avoids this for you in most cases, but there are still some times it cannot be used. Say inheritance for instance). If you’re a bit slow on progressing in mocking tools, this might be a problem as well (It shouldn’t still be though…)

The big problem with non-type safe strings is refactoring, which should happen all the time on your projects. Property names will change, and when these are used as non-typesafe strings in your system it has a few unfortunate consequences:

  • You could break something without knowing it. Worst case is you won’t find it until production

  • The knowledge above could restrain you from doing refactorings.

  • You will have to spend time doing text-searches in the system to find out if and where it is used.

So for a personal project I’m currently playing with, I figured I wanted to do something about it. So I created a small generator project which generates static classes where you have access to the domain objects property names in a type safe manner. What this does for me is:
  • If I do changes to a property of a domain object, and that has been used as a (previously) non-type safe identifier, my compiler will complain.

  • I can do refactorings all the time without worry.

For now it looks for instance like this in use:



This will return “Text”, which is the name of a property in the Resource class or a base class.

I’ll be the first to admit that this is not ideal. Property names as strings are not something you want to deal with, but at times you have no choice, and this feels like the better of the two options.

For those interested in how I chose to solve it:
The generator takes in an input path, a search string and an output path. This is put in a bat-file which is called from the domain projects build. Currently I’ve only implemented a parser for NHibernate mapping files (HBM), which for each class creates a file with each property listed for that class. (I can see situations where you would want to use properties not just used in persistance, but that’s all I need for now). Inheritance is handled by duplicating the properties of the base class in the subclasses.
In short, the file created for the example above looks like:

3 comments:

Anonymous said...

Hi Rune,
Would it be possible to make this code generator available as a zip file?

I have been toying with doing something like you've done so it would be really cool to have a solution already :-)

Thanks
Christian Crowhurst

Rune Sundling said...

Sure, I'm away during the weekend, but I'll add it next week.

Anonymous said...

Thanks Rune, look forward to taking it for a test drive :-)

Christian