I recently say a couple of articles on CodeProject that showcased wrappers to simplify using the CodeDom
http://www.codeproject.com/csharp/CodeDomPatterns.asp
http://www.codeproject.com/csharp/refly.asp
I am in favor of anything that encourages use of CodeDom and tries to flatten the learning curve for using the CodeDom.
Unfortunately, most examples of using the CodeDom seem a little contrived. This makes using the CodeDom seem like over kill.
Consider some of the following applications:
- Using the CodeDom to pro grammatically generate proxy methods for binding parameters to stored procedures
- Using the CodeDom to generate web services for all of the methods in a specified class
- Using the CodeDom to generate code to exercise class libraries by calling every method in the class.
Some advantages of such an approach includes:
- Rich object model makes it easy to structure code generation code.
- As best practices evolve, generated code is easier to maintain. Instead of having to change every web service when a new WSE is available, you only have to modify the generator and then regenerate all of your code. This is much better than having to rewrite every web service.
- Code generated through CodeDom can be rendered as any language that has a CodeProvider. This helps ensure that you will continue to get retrains on your investment in building a generator.
- As new versions of the framework are released, Microsoft will update the implementations of the CodeDom objects to properly support the new version. Code generators that you write will continue to work with new versions of the framework.
There are a couple of things to also keep in mind with maintaining generated code. Never modify generated code. You want to protect your ability to regenerate as needed. Partial classes in version 2.0 of the framework make this easy. Make any customizations in a separate file and then you can easily regenerate the original file without loosing your changes.
In any version of the framework, you can also use inheritance to protect the generation layer. Generate you code and make any code changes in a class derived from the generated class. Not being able to regenerate generated code makes people scared of using code generators. Good object oriented design solves this problem. Code generation does not necessarily lead to bad object oriented design.
Many people frown on the use of code generators because they often produce “ugly“ code, lead to bad object oriented design, or it is unmaintainable. I believe that using the CodeDom avoids these pitfalls and effective use requires good object oriented design rather than precluding it.
Is anyone else using the CodeDom?