I Love Code Generation ' Why Don't You?

Several times over the past week I have had some conversations with folks about code generation, some pro (like me), some con and some that find it scary. My first real exposure to a serious code generation tool was at TechEd 2003 in Dallas. I remember an 8 AM session on the last day given by a Microsoft Engineer from Grenoble France. He showed a tool he called Oly Mars to a packed room. Right then and there I knew I was seeing something I wanted in my daily routine.

The demonstration showed how to point the tool at a database with the application's tables, indexes, keys, etc defined and it would generate stored procedures, DAL, BLL and several user interfaces. The UIs included ASP.NET, WinForms, Mobile and Web Services if I remember it all correctly. All that was left to do was customize the UI's final look and feel and add any customization to the application's code that fell outside of the standard CRUD operations. Think about it, that means you could generate about 85% of the code and focus just on the user experience and custom features.

This experience opened my eyes to something very powerful. Eric J. Smith must have been in the room with me because he soon went on to create CodeSmith, my current code generation tool of choice. I think it has the largest user base and community as well.

I also like Miguel Castro's CodeBreeze and plan on working with it more over the coming months. You can view Miguel demonstrating CodeBreeze on two different episodes of DNR TV, 77, 133.

Visual Studio also has the T-4 generator that is starting to get some traction. I am not a huge fan of it yet and have found it to be rather cumbersome to use. It is the way Visual Studio creates new content for projects, etc. Also do not forget about Visual Studio's Code Snippet library or just adding common textual patterns to a custom toolbox tab.

The Figure above shows how to use Code Snippets in Visual Studio from either a contextual menu (Right Mouse Click). The example shows how to insert a Try Catch Block. It can also be added by typing 'TryC' and pressing the TAB key. More info on using Code Snippets is available on the MSDN site. A Visual Basic Code Snippet editor is also available to help create your own snippets.

Then there are third party add-ins like CodeRush, Refactor and ReSharper (C# tool) that also add code generation and management facilities at our fingertips. If you create either an Entity Framework or Linq to SQL model, those are also code generated. Finally Visual Studio allows you to export entire web sites/applications as project templates or just a form, class or other project file.

All of these tools add value to the development process. And as far as I know all of them allow you to customize templates for code. Most can also be used to generate just about anything that is textual in nature, not just code.

I don't want to get into how various Code Generators work or pros and cons of each one. I do want to discuss why Code Generation is important to an efficient developer and why EVERY developer should be using Code Generation as a standard part of their development routine.

Reduced Time to Market

This should be obvious, but is not necessarily a truth. On just about every application I develop I generate around 80-85% of the final code in one way or another. This obviously means I can typically create a brand new site from scratch much faster than if I did everything by hand. But, as I will discuss a little later, it leads to adding more functionality or improving the UI itself.

Here is where many developers get scared. They assume that because 80% of their application can be generated in literally seconds they will soon be out of a job. This is far from the truth, in fact it should help them keep their job. Any employer that does not see the value in developers using code generation in their standard routine is probably not one you really want to work for in the first place.

Think about how much more valuable you are using Code Generation over say outsourcing it to cut and paste developers for $10 an hour. You are also adding value by following (your) standard design patterns for your code. And ultimately you do not waste time on routine coding work, like a Data Layer for example. You spend your time working on the real business code or the parts that really make the difference in the application. Anyone can make a standard CRUD application, that code is the first thing that should be code generated. That means a developer using code generation does not waste their time and thoughts on mundane code.

Working with as many small businesses as I have over the last decade I learned early on they want something they can touch and play with within hours of signing a contract with me. Technology scares them and they need to be comforted you are producing a site for them. Having something for them to touch the next day is a huge confidence factor. I have also found this fact to hold true for larger businesses as well. This is where writing a bunch of unit tests before writing any application code will cause a lot of tension with customers, and that is my opinion based on my experience. So having a solid set of code generation scripts is a huge gain.

Reduction of Errors

I was having a conversation with one of my peers on unit testing a few weeks ago. In that conversation I asked if I should code gen unit tests for my generated code? A true TDD conformists would say never, but my friend and I were on the same page that if I had already tested the pattern that I generate code from there was little to no value in writing a unit test from scratch for that code. In reality it would generally be an integration test and not a true unit test in most cases. So having some tests to verify everything is working is a good idea, so I do not want to discount the value of having the tests.

But unit tests are there to help developers reduce development time (at least in theory) and errors sent to Q&A and production. To me code generation serves the same purpose, but in reality, not theory. To me unit testing and code generation have a symbiotic nature in the code development process. When I create a new coding pattern I have to test it in one way or another to make sure it works. Once I am satisfied with the pattern I then I create or add the pattern to my code generation scripts.

By using this proven pattern that is replicated through code generation templates I reduce the chance I make typos and other bugs while writing code. For example I do not forget to add caching code in a get method of a repository. Or maybe a try catch block or data validation routine, etc.

The following code is a standard method pattern I use to get a list of entities from a database. There are two features it has that are 'optional'; caching and filtering for active records. This is real code generated from a Code Smith template, which is in the screen shot above. I did not have to write one single character in this method by hand.

Public

Function

Getinforeqs(

ByVal

vActive

As

Boolean

)

As

List(Of ContactRequest)

Dim

key

As

String

= CacheKey &

"_List"

&

"_Active_"

& vActive

If

EnableCaching

AndAlso

Not

IsNothing(Cache(key))

Then

Return

CType

(Cache(key), List(Of ContactRequest))

End

If

Dim

lContactRequests

As

List(Of ContactRequest) inforeqctx.ContactRequests.MergeOption = Objects.MergeOption.NoTracking

Dim

tempList

As

IQueryable(Of ContactRequest) = (From lContactRequest

In

inforeqctx.ContactRequests)

If

vActive

Then

tempList = (From lContactRequest

In

tempList Where lContactRequest.Reponded =

False

)

End

If

lContactRequests = tempList.ToList

If

EnableCaching

Then

CacheData(key, lContactRequests, CacheDuration)

End

If

Return

lContactRequests

End

Function
 
I like to show this method when talking about Code Generation because it has evolved over the years. At its core it was essentially a 'Select * from X' type of wrapper. As I added functionality to the method and made sure the patterns worked, I updated the code generation template. I can have full confidence the generated method will work without testing.
 
You can still create integration tests for this method, but I would simply code gen those as well. If I think of a new way to test the method I will add it to my testing script too. So ultimately using code generation drastically increases the quality of my code and ultimately my applications.
 
There is a down side and that is replication of bad code. Yes there it is, if you have a script that generates a method with buggy or just smelly code you will replicate it everywhere, right? Yes you will. But I have found this to not be a real issue because I try my best to put my generated code into partial classes. By leveraging a partial class I can create one file that is fully maintained by code generation and one that is custom code and maintained by me. If I find I need to regenerate the code I can do it, feel confident in it and just replace the entire file or method from the regenerated code without breaking my customizations. Remember it takes only a few seconds to generate an entire DAL and BLL layer for my applications. Where I do have a problem is in the user interface code, and I have learned to live with it since it is so highly customized once it is generated in the first place.

Increased Product Functionality

Now that I have talked about reduced development time and increased quality I can talk about the product of the first two, increased product functionality. If you think about it, a 6 week project where you can generate 85% of the application's code in a few minutes leaves you with a lot of time to improve functionality.

There are always custom queries and methods that every application needs to make it unique. How well those features are developed and matured makes a big difference as to how well the application is accepted by users.

There is also a lot more time to sculpt and refine the user interface and experience. This is becoming so important these days as users are expecting more and more richness in applications. If you had to spend that time writing the plumbing and wiring code the application you will have a hard time achieving that rich interface.

Summary

These are my primary observations of using Code Generation in my daily development practice for over 5 years. I know there are many more points I could have made, but I want to hear from you. So please comment either way with your opinions of code generation.

Share This Article With Your Friends!