hide all comments

DSM-tech

Generating code from models

May 24, 2005 17:07:18 +0300 (EEST)

A user in Microsoft's help forums for their DSL Tools beta asked how to use the templating / code generation facilities to navigate via relationships in a model. Here's how you do it in Microsoft's DSL Tools:

<h2>ConceptBs</h2> 
<%
foreach ( ConceptB b in this.ConceptA.Bs ) 
{ 
%> 
<h3>Name: <%=b.Name%></h3> 
<h3>Outgoing links:</h3>
<%  
    MetaRoleInfo roleInfo = b.Store.MetaDataDirectory.FindMetaRole
(BReferencesB.ReferringBsMetaRoleGuid);

   if (roleInfo != null)
   {
      foreach (object link in b.GetElementLinks(roleInfo))
      {
         BReferencesB relationship = link as BReferencesB;
         if (relationship != null)
            {
%>
      
<p>Refers to: <%=#relationship.ReferencedB.Name%></p>
      
<%
         }
      }
   }
} 
%>

And here's the same thing in MetaEdit+ (assuming I was able to decode the above reasonably accurately):

'<h2>ConceptBs</h2>';
foreach .ConceptB
{
   '<h3>Name: '; :Name; '</h3>';
   '<h3>Outgoing links:</h3>';

   do ~From~To.ConceptB
   {
      '<p>Refers to: '; :Name; '</p>';
   }
}

The key difference here is in the line in the middle, "do ~From~To.ConceptB". Starting from the outer loop's current ConceptB, it says to crawl along any From role and its To role into the next ConceptB. That one line replaces twelve lines from the Microsoft version (everything between "Outgoing links" and "Refers to"). 

This kind of pattern is very common in any code generation or reporting on a model. Users of Microsoft's tools will thus quickly find their code full of blocks of code very similar to the above. That's ironic in a tool intended to save developers from such unproductive code duplication.

Whilst I'm always against needlessly creating new languages, in some cases existing languages simply aren't up to the task. That's true for UML when it comes to representing software at a high level of abstraction and allowing full code generation - as Microsoft have recognised - but it's also true for standard programming languages applied to the task of turning model structures into text.

The idea of the MetaEdit+ Report Definition Language is to be simple to learn, fast to use for common tasks like the above, and powerful enough to allow generation of full production code from models. Each customer's expert developer has their own idea of what the code should look like, and even for two companies building virtually identical products that code can be completely different. Having a good tool that allows you to concentrate on the task of turning models into code, rather than on the code you need to write to do that, seems to help a lot in terms of customer acceptance. But of course for those who'd rather work in a generic programming language, you can always access the models via the API or by manipulating them in XML format, as with Microsoft's DSL tools.