Posts Tagged ‘ Languages ’

OT2004 : Elegant Implementation of Null Objects

Since Dan and I have both been working together again (2 years at ThoughtWorks) and since I moved into a house less than ten minutes walk from his, we very rarely see each other. So it was good fun to have a geeky catch up session and play with some code.

Something Dan showed me:

interface Something {
Something NULL = (Something)Null.object(Something.class);
// more stuff…
}

The Null class is a simple dynamic proxy that will return an immutable null object that does nothing. Methods that return values will return default primitives (0, false), empty arrays or more dynamic proxies.

So at any point in the code you can call Something.NULL to get the null implementation.

Nice! (Dan, upload it somewhere!)
Update: He did – http://proxytoys.codehaus.org/

OT2004 : Generic Mechanisms in Software Engingeering

This workshop, hosted by Simon Davies, and chums from Microsoft (with a bit of Bruce Anderson), was a thinking excercise about the pros and cons of some of the language features of C# (and conveniently also Java) including generic types, attributes and dynamic code generation.

We were given some sample scenarios to which we had to contrast the approaches of using these features in isolation and combined together, taking into account ease of development, runtime performance, flexibility, maintainability and simplicity:
* Creating a strongly typed list.
* Serializing objects to XML (a subject I’m familiar with).
* CRUD persistence of domain objects to a database.

This was quite thought provoking. While it was very easy to see the advantages of using generics to implement a strongly typed list, experimenting with all the different approaches was a fun exercise. Code generation may be less simple but offers better runtime performance.

It was fun brainstorming ideas with developers from different backgrounds and seeing which approaches appealed to them.

I was also shown the anonymous delegate feature in the next version of C#. Mmmm closures…

// usage
int totalAge = 0;
peopleFinder.All(delegate(Person person) {
totalAge += person.Age;
});

// implementation
class PersonFinder {

public delegate PersonDelegate(Person person);

public void All(PersonDelegate delegate) {
some magic iteration code {
Person person = ...;
delegate(person);
}
}

}

Now for a staticly typed language, that’s a lot cleaner than I was expecting.

This is something I’m really excited about as it’s the style of development I use all the time in Java, without all the syntactic cruft of anonymous inner classes. And I’m sure it’ll appeal to all the Ruby/Smalltalkers out there.

Something else I learned is that (unlike Java 1.5), generic definitions are available at runtime.

Plenty more info in the C# 2.0 specification.

How to do Dynamic Proxies in C#

Background: A dynamic proxy dynamically generates a class at runtime that conforms to a particular interface, proxying all invocations to a single ‘generic’ method.

Earlier, Stellsmi asked if it’s possible to do this in .NET (it’s a standard part of Java). Seeing as it’s the second time I’ve talked about it in as many days, I reckon it’s worth blogging…

As far as I know, there are two ways to do this:

* Using the magical RealProxy class that monkeys with the context (whatever that means). This requires that the object that is being proxied must extend ContextBound.
* Using Reflection.Emit to generate a new class at runtime that overrides/implements the necessary methods and dispatches invocations to a generic handler. This can implement an interface or override any virtual method.

The first approach is pretty trivial, but it locks you into the fact that you can only proxy objects that extend ContextBound. Not ideal as this pulls a lot of stuff into your class you don’t necessarily need and prevents you from inheriting something else.

The second approach is more suitable, less intrusive, but not pretty to write as it involves writing low-level IL op-codes. However, I did this already in NMock and at GeekNight, Steve and Jon lovingly decoupled the ClassGenerator from the core of NMock, so you can create generic dynamic proxies. So now it’s easy to create a proxy.

h3. Example

Here’s an interface you want to create a dynamic proxy for:

interface IFoo {
string DoStuff(int n);
}

Note:

* You can use one invocation handler to handle all method calls in the interface. The example above only has one method for clarity.
* This doesn’t have to be an interface. It could be a class, so long as the methods you want handle are all marked virtual (sigh).
* You can do the same thing for properties as well as methods.

To create the proxy, you need to create an implementation of IInvocationHandler. This is called any time a method is invoked on the proxy.

class MyHandler : IInvocationHandler {
public object Invoke(string methodName, param object[] args) {
return "hello from " + methodName;
}
}

Notes:

* The name of the method being called and parameters passed in are passed to this handler.
* Whatever is returned by the Invoke() method is returned by the proxy.
* If the method is of type void, just return null.

Finally, you need to generate the proxy itself so you can actually use the damn thing:

ClassGenerator generator = new ClassGenerator(
typeof(Foo), new MyHandler()  );
IFoo fooProxy = (IFoo)generator.Generate();

string result = fooProxy.DoStuff(2); // returns "hello from DoStuff"

Ermm and that’s it! Use your dynamic proxy like it’s a real class.

ClassGenerator is part of the NMock library. Use it for AOP style interceptors, decorators, stubbing, mocking :), whatever.

Brain rumblings… Hmm… maybe that should be a delegate instead… maybe I should revisit some stuff…

Running Groovy natively without the JVM

Two days ago I was hacking away at some Ruby scripts and thought it would be nice if I could write them in Groovy (not necessarily useful, just nice).

Of course, for small scripts that honour the UNIX philosophy, that would be a terrible idea. These scripts should start instantly and have minimal overheads.

What changes would be needed to allow Groovy to compete with languages like Perl, Python, TCL, Ruby or plain old shell scripts in this space?

* Better performance / reduced overheads (cpu, memory, start-up time).
* Simple install (src tarball, RPM, dpkg, windows installer, OS-X whatever).
* No JVM required.
* Ability to use Groovy to access less Javaish libraries (POSIXy style stuff, MFC, .NET).
* Ability to use Groovy (and Java) objects from other languages (C, C++, Perl, Python, Ruby, .NET, etc)

As an experiment, I’ve created a subproject of Groovy (groovy-native) that aims to address these issues.

Take a peek at where I’m going with this.

So far:

* Created a stripped down native runtime library (libgroovy.so).
* Compiled a .groovy file to a native executable (linked with libgroovy).
* Created a native C++ app that calls interops with Groovy objects.