Posts Tagged ‘ Languages ’

Node.JS would really benefit from LibFFI

Having recently built a simple LDAP library that required a bit of C++, I think Node would really benefit fromĀ LibFFI bindings.

LibFFI allows C functions to be called dynamically at runtime from another language. There are LibFFI bindings for Python (ctypes), Ruby (Ruby-FFI) and Java (JNA), amongst others.

If FFI bindings existing for Node, you’d be able to call native C functions without ever leaving the comfort of JavaScript. Apart from making the code a lot simpler, it also avoids the need for a build step (nothing to compile), and hide the complexities of working with threads in C++.

Here’s how it would work…

Step 1: Write some JavaScript that bindings to a native library and exports C functions as JavaScript.

var ffi = require('ffi'); //
var ldap = ffi.createLibrary('ldap', { // load libldap.so
  // exporting these functions
  // (C function name, [C arg types], C return type)
  open: ffi.exportAsync('ldap_open',
    [ffi.string, ffi.string], ffi.pointer),
  simpleBind: ffi.exportAsync('ldap_simple_bind_s',
    [ffi.pointer, ffi.string, ffi.password], ffi.int),
  unbind: ffi.exportAsync('ldap_unbind',
    [ffi.pointer], ffi.integer)
});

Yes, this looks messy, but it’s a lot less painful than doing it in C++.

Step 2: Call your native libraries through the JavaScript bindings.

ldap.open('somehost', 389,
  function(err, ldap) {
    if (!err) {
      ldap.simpleBind(ldap, someUserName, somePassword, 
        function(err, result) {
          if (!err) {
            print('Authentication result = ' + result);
            ldap.unbind(ldap);
          }
        }
      });
    }
  });

The native functions would still execute asynchronously in a background thread, so as not to tie up the main Node event loop. The usage pattern is the same as the rest of Node.

Writing the code still involves a basic knowledge of C, in that you need to read the documentation for native libraries and understand what it means. But you’d write all your code in JavaScript and avoid the hassle of the build system and platform specific linking.

There’s a lot of native libraries out there – this would open up a lot of doors.

Who’s going to take a crack at it?

VB.Net is the bestest

I was happily coding away in VB.Net today (grrr) when I noticed a little weirdity in the intellisense popup.

stupid.gif

Documentation says:

The NotOverridable modifier defines a method of a base class that cannot be overridden in derived classes. All methods are NotOverridable unless marked with the Overridable modifier. You can use the NotOverridable modifier when you do not want to allow an overridden method to be overridden again in a derived class.

Makes C++ look simple.

Accessing generic type information at runtime

A common misconception about generics in Java 5 is that you can’t access them at runtime.

What you can’t find out at runtime is which generic type is associated with an instance of an object. However you can use reflection to look at which types have been staticly associated with a member of a class.

public class GenericsTest extends TestCase {

class Thing {
public Map stuff;
}

public void test() throws Exception {
Field field = Thing.class.getField("stuff");
ParameterizedType type = (ParameterizedType) field.getGenericType();
assertEquals(Map.class, type.getRawType());
assertEquals(String.class, type.getActualTypeArguments()[0]);
assertEquals(Integer.class, type.getActualTypeArguments()[1]);
}

}

Just wanted to clear that up.

(This is something that I’ll probably exploit in XStream for J5 users to further simplify the XML.)

The power of closures in C# 2.0

Martin Fowler (obligitary Fowlbot namedrop) recently blogged about the power of closures in languages that support them. It’s worth remembering that C# 2.0 has true closure support in the form of anonymous delegates. This includes reading and modifying variables outside the context of the closure – unlike Java’s anonymous inner classes.

Just for kicks, I’ve rewritten all of the examples Martin’s Ruby examples in C# 2.0. This makes use of the improved APIs in .NET 2.0 pointed out by Zohar.

Ruby C# 2.0
def managers(emps)
return emps.select {|e| e.isManager}
end
public List<Employee> Managers(List<Employee> emps) {
return emps.FindAll(delegate(Employee e) {
return e.IsManager;
}
}
def highPaid(emps)
threshold = 150
return emps.select {|e| e.salary > threshold}
end
public List<Employee> HighPaid(List<Employee> emps) {
int threshold = 150;
return emps.FindAll(delegate(Employee e) {
return e.Salary > threshold;
});
}
def paidMore(amount)
return Proc.new {|e| e.salary > amount}
end
public Predicate<Employee> PaidMore(int amount) {
return delegate(Employee e) {
return e.Salary > amount;
}
}
highPaid = paidMore(150)
john = Employee.new
john.salary = 200
print highPaid.call(john)
Predicate<Employee> highPaid = PaidMore(150);
Employee john = new Employee();
john.Salary = 200;
Console.WriteLine(highPaid(john));

The code difference between the languages isn’t that difference. The C# 2.0 code is obviously longer (though not a lot) because:

  • C# 2.0 is staticly typed (let’s not get started on the static vs dynamic debate).
  • C# 2.0 requires the ‘delegate’ keyword.
  • Ruby allows you to ignore the ‘return’ keyword.

You can try this stuff out yourself by playing with Visual C# Express.

A simple way to access JavaDoc attributes at runtime

It’s easy to gain access to JavaDoc attributes using QDox, however this requires you to have the source available. At runtime this isn’t always possible, unless you’re happy giving your source away.

A workaround to this is to use QDox to parse the source code at development time and serialize the resulting structures to make them available at runtime. This will work, but it’s a bit nasty as big binary files aren’t the most stable of things.

A more open approach is to bundle the source of your classes with the application, making them available at runtime, however *without* the method body implementations.

*Class with method body implementations:*

package stuff;

public class CheeseSlicer {

/** @transaction mode=isolated */
public Slice feedMe() {
// some implementation specific stuff here.. don't waste your time reading it.
if (System.currentTimeMillisMillis() % 2 == 0) {
return new CheddarSlice();
} else {
return new BrieSlice();
}
}

}

*Class WITHOUT method body implementations:*

package stuff;

public class CheeseSlicer {

/** @transaction mode=isolated */
public Slice feedMe();

}

To do this is simple. First, QDox can be used to parse the source of a class into a JavaClass. Calling JavaClass.toString() will print out the class without the body implementations (as above). This is something done at development time and the result should be written to a file that is available at runtime.

At runtime, QDox can read this file just as if it were a full-blown Java source file, making the attributes available.

JDK 1.5, of course, makes this redundant, but in the mean time…

OT2004 : Delegation in Java

Ivan Moore is blogging about it here.

OT2004 : Taming the Tiger (Java 1.5)

This session was presented by Benedict Heal, and he was brilliant; concise, clear, humourous and extremely chilled out. Even the fact that Josh Bloch was listening in on his presentation didn’t phase him.

Most of the new Java 1.5 features are already widely known. Generics, annotations, auto-boxing, enums, syntactic sugar, yada yada yada.

Some things that caught my eye:

* -Xlint : a compiler flag to warn you when your code can be improved to take advantage of new features such as generics.
* Generics are not available at runtime (unlike C#).
* Use of generics all over the API, not just collections. For example, Class is a genericised type, so newInstance() returns the correct type.
* List<MyThing> cannot be given a List<ExtendedMyThing>. Makes sense really as otherwise you’d be able to add things that it shouldn’t allow.
* Genericised types can be constrained to only allow certain type. class Blah<T extends MyThing>.
* Wildcards allow even more flexibility: List<? extends MyThing> list = new ArrayList<ExtendedThing>() // valid.
* Or this: List<? super ExtendedThing> list = new ArrayList<MyThing>(); // valid
* Generics are complicated :)
* Annotations can be specified as source level, class level (available for inspection by class loader) or runtime level (available through reflection).
* Variable parameters to a method. Defined like this: printf(String format, Object… args). The three dots are part of the syntax! Called like this: out.printf(“Blah % blah % blah”, 44, “hello”, someObject). Note autoboxing comes into play too.

It’s only a shame there isn’t a feature such as the anonymous delegate in C#… now that is real power. Rock on Java 1.8.

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…