Pages

A peek into metaprogramming

Metaprogramming is about programming acting on other programs. Modifying the programs on the fly. Consider a compiler which is a program written to act,parse,execute the code written, analyzed on grammatical domain of its own lexical structure. It interacts and compose programs of small code components like importing required classes, #define macros, message passing etc. when we are to discuss about compilers, they are translating the source to it machine representation. In meta programming, its about source to source and machine independent. In C++, there are templates which is a data object for a set of programs,generates the code that is executed. The compilers use the program analysis method of type system, a check for the type correctness.an oracle, that is,some method for checking whether the system under test has behaved correctly on a particular execution. It is the assertions embedded in the code.Many programs read an input sequence and produce an output sequence, maintaining a logical correspondence between the input and output structures. When the type come into picture in a dynamic way,the system needs to be intact. This is being handled by the compiler itself as it asserts the type. Usually a program will have a structure ; a syntax tree,like an AST.The meta programs can manipulate these representations. The abstract syntax can then be used as an intermediate language, such that multiple languages can be expressed in it, and meta-programs can be reused for several source languages. Functional languages can have polymorphic higher-order functions take other functions as arguments and returns functions, treating functions as values. Java uses AOP, which introduces pointcuts to a program that can then be modified at runtime (using bytecode manipulation etc).

Take, Javascript, we can attach additional properties to an object ("expando").


var testObject = {};
testObject.variable1 = 'string';
testObject.variable2 = 3;


The type system is dynamic.

It has functions as first class objects.


testObject.functionA = function(){};

Function can return other functions as well as passed in as parameters.


testObject.functionC = function(functionA){ return functionB(){};};


Closure occurs when a function is defined within another function,and the inner function refers to local variables of the outer function. Currying a function is modified with each call so that the arguments passed into it become part of the function which will be helpful in partially evaluating functions. It is implemented using closures.

for the simple stupid code ,


function show(){

alert(testAB('A','B'));//AB
var testB = testAB('A');
alert(testB);
alert(testB('B'));//AB

}

function testAB(a,b){
if (arguments.length < 1) {
return add;
} else if (arguments.length < 2) {
return function(c) { return a + c }
} else {
return a + b;
}
}

In Groovy,


def testAB = { a, b -< a + b }
assert testAB('A', 'B') == 'AB'// or testAB.call('A','B')

def testB = testAB.curry('A')
assert testB('B', 'World') == 'AB'


In Groovy,each object has it is own meta class defines the behavior of any given Groovy or Java class.Alter the metaclass (getMetaClass()) and change the object's behavior at runtime. A special MetaClass called an ExpandoMetaClass that allows dynamically adding methods or properties.


String.metaClass.echo = {->
return "This is an echo"
}

println "Test".echo() //will print This is an echo.



String is final, even methods can be added !

The behavior of program changes with a concise code.Instead of test driven development,the methodology of behavior-driven development do follow test-first code-writing. In this case tests are considered specs, or "expectations" about how code will behave. Its is checking what code should do, than what it had done. To understand the concepts and practical uses, need to explore more

Groovy and some Griffon experiments

Groovy is dynamic with its superset java syntax to have fun with and be productive.It can be compiled to bytecode in .class and interpreted at runtime as a script.Adds closures,dynamic typing (duck), auto imports,no semicolon,no return... like a ruby-fied java.There can came railing Grails.Griffon for desktop, is very similar to developing web applications with Grails, basically the MVC + "convention over configuration".In Griffon, the Model is a POGO,the view is SwingBuilder and the controller (injected to) manage the Model and View together ().We know the applet coding and managing is cumbursome, for eg an applet form populated by an OrderDO etc.The coupling of model logic along with the applet controllers is mostly seen in web applications.So I decided to have some fun on this cute creature,Griffon.

A quick work around to display a bindable xml to the text area.I tried with tables, but some issues with events, so I will try later.Developing is easy and with less code.Scripting makes a flexible (agile) application layers like views and controller.Groovy can act as a super glue for different layers.It could combine XML parsing,widgets,networking...Each widget node written in the view classes is syntactically a method call.All of these method calls are dynamically dispatched.Most don’t actually exist in bytecode.Child closures create hierarchical relations.Closures are first class objects.This hierarchy of components would normally be created through a series of repetitive instantiations, setters, and finally attaching child to its respective parent.Child widgets are added to parent containers.
Like a ScrollPane having a text area etc.An event listener method is equivalent to adding a listener with that method; actionPerformed : { ... } ;in Groovy.

For this same Java does as

button.addActionListener(new ActionListener() {
void actionPerformed(ActionEvent evt) { ...}
})

Samples



source
Download source
Follow the quickstart guide and run the app from griffon-test directory

Groovy rocks!! says http://onestepback.org/articles/groovy/index.html

More here
http://groovy.codehaus.org/Griffon+Quick+Start
http://groovy.codehaus.org/Swing+Builder
http://griffon.codehaus.org/

JiBX - Part 1

When we consider XML as a data model while programming, focus is mostly given on strings/tags/elements in parsing data.The ETL operations are done on this ubiquitous document interchange model when communication is made between applications.To make things simple in the internet; which is fond of documents ; XML became the foundation of services through web.The object, which is accessed from object graphs in the memory have features such as inheritance / polymorphism and attributes / object-based relationships while XML does not have any of these features as objects have.It is merely a grammatical (hierarchical) representation of data with all its branches mangled to itself .But they have similarity in the sense of representation of real world data.Therefore they can exists as the representation of each other which eases in programming.They are effective in defining business uses cases.But there is an impedance mismatch between objects and xmls.An application written in Java, will have it data types defined within the scope while XML Schema which defines the data is richer than Java.Complex objects find difficulty in serializing.Have a look on this paper which explains the X/O impedance mismatch.

We can generate Java classes from XML or vice versa.In this case, it is a "Schema-Centric" approach.We define an XML schema.Then one or more XML documents.Then generate java classes based on them.In this case you need a stable schema which can be used to validate data.Essential for a "reliable" web service.But application code is forced to use an interface that reflects the XML structure which makes them tightly coupled to contracts defined.Any change in schema make a need to regenerate the object model and change application code to match.

If we map the classes using bindings, then its "Java technology-centric " approach.This can be adopted when you don't want object model tied to schema.When there is a need to support different versions of the schema with the same object model or a common data exchange format for existing objects is needed.Binding definitions are themselves XML documents, with a schema defined for it.

JiBX is fundamentally a Java technology-centric (mapped binding) approach uses binding definitions.You define how XML relates to Java objects.Start from schema, code, or both.Binding code is compiled (or wired ?) into files (which uses BCEL byte code enhancements ). It can be done at build time, or on-the-fly at runtime.This makes JiBX compact and fast.JiBX achieves its performance by using post-compilation bytecode manipulation rather than the reflection.The advantage is that there is no need for getters, setters and no-arg constructors.One can write the class without considering mapping issues and then map it without modifications. XML schema describe domain objects.JiBX really maps well to XSD. JiBX is based on a XML pull parser architecture (XPP3) . Rather than generating code from a DTD or Schema, JiBX works with a binding definition that associates user-supplied classes with XML structure. The binding compiler is executed after code is compiled and the marshalling/unmarshalling code is added on to the class files.There are tools along with it, like Bindgen that can generate schema from existing classes.


Tutorials

http://jibx.sourceforge.net/binding/tutorial/binding-start.html
Pdfs - JiBX -Part1 JiBX-Part2 Intro

Previous articles
Creating a Java WebService using Axis 2 (a lazy approach)
A simple RSS parser