|
Writing a Code Generator in Java
Design and implement a flexible, Java code-generation system that is easy to maintain, intuitive to work with, and based on IOM
by Giuseppe Naccarato
Posted March 3, 2004
Editor's Note: This is the first of two installments on using Java to write a code generator. This first installment defines a code generator, lists its benefits, and begins providing guidelines for designing and implementing a generic code generator. The article also looks at the code generator's architecture and Internal Object Model. The second installment concludes with a discussion of the importer and exporter interfaces, manual implementations, and using templates.
A code generator is a program that has a model as input and produces output source code, which implements that model. The model consists of a set of metadata containing information about the code that will be generated. A model can be a Unified Modeling Language (UML) design, a proprietary descriptor file, or even other source code. The model format can be XML, plain text, CSV, or other kinds of sources such as directories, databases, or repositories. Starting from the information contained in the model, a code generator creates source code, which belongs to a programming language (C, C++, Java, C#, VB, and so on) or to another type of output: documentation, descriptors, configuration files, SQL code, and so on.
Generating code brings a number of benefits. When applied to the right context, code generation increases productivity; in fact, generating code should be faster than writing it by hand. Generated code is usually consistent; a program that writes code, unlike an inattentive programmer, always follows the coding standard. Therefore, class, method, attribute, and parameter names should always be consistent. A further benefit of code generation is related to abstraction. Basically, the code is the implementation of an abstract model, and therefore the system is not bound to a specific target-technology platform. Finally, you may have concerns about the quality of the generated code. Don't be afraid. Since programmers write generators, the quality of the generated code should be at least as good as what the same programmers can write manually. In addition, using templates, as you will see, assures a good quality and easily maintainable generated code.
The focus here is to provide guidelines about how to design and implement a generic, flexible, and effective code generator in Java. Although the concepts will be generic and usable for different kinds of input and output, the examples show how to translate a simplified UML class diagram into Java code. For space reasons, some listings will be partial. However, you can follow this link to download the complete implementation of the code generator.
Back to top
|