Today I released a library that adds multimethods to Java and .NET. Multimethods give you the ability to call methods based on the runtime type of arguments, eliminating the need for the Visitor pattern. They can help you write code that is loosely coupled, less verbose and easier to understand.

I tried to make the library as straightforward to use as possible. To call a method (in Java), simply write:

Multimethod.call(/*return type*/, /*target object*/, /*method name*/, /*arguments*/)

For example:

Multimethod.call(Shape.class, this, "intersect", new Rectangle(10, 10), new Circle(5))

Multimethod.call will dispatch to a method that matches the arguments in the most type-specific way, automatically detecting ambiguities. It will also dispatch based on the number of arguments, and will perform boxing/unboxing as necessary.

You can get the library from its github repository, packaged up and ready to use in Java, .NET 3.5+ or Silverlight for Windows Phone 7. Don’t forget the check out the reference and tutorials in the project wiki.

Hopefully, multimethods will make your life a bit easier. Happy coding!

Comment now!
















Trackbacks