Exams are over, project remains


Tux, the Linux penguin
Image via Wikipedia

Today saw my last exam for the MSc, though I still have to complete the project.

So, lots of posts about Linux page management to follow – I hope.

Advertisements

Interceptors in Groovy


The codehaus website has been down all day, which is more than a little painful when one has an exam on Groovy tomorrow and there is not even a recommended text book for the course (and, as I have discovered, the lecture notes seem to have more than a few errors and omissions).

So here is my attempt to explain to myself (and anybody who stumbles across this) how method interception works in Groovy.

First of all we have to implement the Interceptor interface. This has three methods:

  • beforeInvoke()
  • doInvoke()
  • afterInvoke()

The signatures are:

Object beforeInvoke(Object obj, String methodName, Object[] args)

boolean doInvoke(void)

(this must return true if the method is to be invoked)

Object afterInvoke(Object obj, String methodName, Object[] args, Object result)

The created interface then has to reference to the class being intercepted via use of the ProxyMetaClass eg

def myProxy = ProxyMetaClass.getInstance(myClass)
myProxy.interceptor = new MyInterceptor()

and then via the use keyword

myProxy.use {
def myObj = new myClass()
myObj.someInvocation()
}

Here’s a toy but working example:

Integer.metaClass {
getFibonacci {
fib = delegate
def fibno = 0
while (fib) {
fibno += fib
fib–
}
return fibno
}
getSquare {
return delegate * delegate
}
getFivepercent {
return delegate * 0.05
}

}

class FibInterceptor implements Interceptor {

def beforeInvoke(Object obj, String methodName, Object[] args) {
print “beforeInvoke: Value is $obj, method is $methodName, arguments are $args”
println()
}

boolean doInvoke() { println “In action…”
return true}

def afterInvoke(Object obj, String methodName, Object[] args, Object res) {
println “After: value is $obj and the result was $res”
return res
}
}

def myProxy = ProxyMetaClass.getInstance(Integer)
myProxy.interceptor = new FibInterceptor()

Integer x = 2
myProxy.use {
println “X is $x and its Fibonacci number is ${x.fibonacci}, its square is ${x.square} and five percent of x is ${x.fivepercent}”
}

Giving output:

beforeInvoke: Value is 2, method is asBoolean, arguments are []
In action…
After: value is 2 and the result was true
beforeInvoke: Value is 0, method is plus, arguments are [2]
In action…
After: value is 0 and the result was 2
beforeInvoke: Value is 2, method is previous, arguments are []
In action…
After: value is 2 and the result was 1
beforeInvoke: Value is 1, method is asBoolean, arguments are []
In action…
After: value is 1 and the result was true
beforeInvoke: Value is 2, method is plus, arguments are [1]
In action…
After: value is 2 and the result was 3
beforeInvoke: Value is 1, method is previous, arguments are []
In action…
After: value is 1 and the result was 0
beforeInvoke: Value is 0, method is asBoolean, arguments are []
In action…
After: value is 0 and the result was false
beforeInvoke: Value is 2, method is multiply, arguments are [2]
In action…
After: value is 2 and the result was 4
beforeInvoke: Value is 2, method is multiply, arguments are [0.05]
In action…
After: value is 2 and the result was 0.10
X is 2 and its Fibonacci number is 3, its square is 4 and five percent of x is 0.10

 

Meta programming: giving Integers a “fibonacci” property in Groovy


A tiling with squares whose sides are successi...
Image via Wikipedia

So, you just decide that each Integer should have an automatic property of knowing it’s Fibonacci number, well now your wish is granted:
Integer.metaClass.getFibonacci {
     fib = delegate
     def fibno = 1
     while (fib) {
         fibno += fibno
     fib--
     }
     return fibno
}

     Integer x = 25
     println x.fibonacci

I admit this is probably not the most useful additional property one could add to an integer and, of course, it is a function of an integer and not a property, but that was not my point…

The “use” mix-in in Groovy


Punch card from a typical Fortran program.
Image via Wikipedia

Here’s a code example:

Class StringMulti {
        static def multi(def self, args) {
        def z = self.toInteger()
        args.each{
            z *= it.toInteger()
        }
        return z
    }

}

use (StringMulti) {
        def y = ["343", "98", 98, 100]
        def x
        x = "1".multi y
        println x
}

The “use” mix-in allows the static methods of the class specified in use to be mixed in to the classes – with the first parameter of the mix in replacing self in the example above.

Behavioural software patterns


These patterns cover algorithms and the assignment of responsibilities between objects.

Iterator – this pattern is concerned with allowing iterative access to a composition without exposing the underlying implementation.

Typically an iterator is an abstract interface and the composite object creates a concrete iterator that implements it – but the iterator interface is what is used by other objects.

Mediator – the mediator pattern is concerned with ensuring loose coupling between objects by defining interfaces that allow them to interact without knowledge of each others’ internals.

Observer – this pattern defines a one-many dependency in which one object – called the subject – notifies subscribing objects of changes in its state.

UML to describe the Observer pattern
From Wikipedia

State – this pattern is about allowing an object to change its behaviour when its state changes. The object will appear to change its class.

The Gang of Four give the example of a TCP connection – which will respond differently to datagrams depending if it is in the LISTEN, ESTABLISHED or CLOSED state. In each of these cases a different subclass will handle behaviour, though a common interface is used by all three.

UML for state pattern
From Wikipedia

Strategy – this pattern allows objects with different algorithms to operate through a common interface. Typical examples in text books and lecture notes are including paper aeroplanes and rubber ducks in collections of aircraft and avians!

So, for instance, all aircraft may have a fly() method in their abstract interface, but the concrete implementation for the paper aeroplane implements behaviour appropriate for that type of craft.

UML for strategy pattern
From wikipedia

Template Method  – this pattern creates a skeleton for an algorithm but allows subclasses to over-ride specific parts.

Template method UML Class Diagram
Image via Wikipedia

Visitor – the visitor software pattern is concerned with allowing new algorithms to be applied to an object without changing the object itself. Instead a new visitor class implements the visitor interface. In this way many new methods can be dynamically added to a class.

Class Diagram for the Visitor Pattern
Image via Wikipedia

Structural software patterns


After a short digression into the prospect of an asteroid ending human civilisation and so making my Object Orientated Design and Programming exam on Tuesday something of a waste of effort, I am back to using the blog as a notepad and revision resource.

From the Gang of Four’s Design Patterns , I want to look at some of the structural software patterns: these are the patterns that cover issues such as composition.

The Adapter or Wrapper pattern allows classes that could not otherwise work together, work together, by converting the interface of one class into that which is expected.

The GoF use the example of integrating an “off the shelf” text editing component into a graphics package. The text editor may not have the interface that matches the graphics package, but an adapter can allow the two to work together.

A UML diagram of the Object Adapter design pat...
Image via Wikipedia
From wikipedia

Hopefully the bit of UML above makes it clearer – the client class calls the adapter in its doWork() method, and it in turn calls the correct method in the adaptee. This is the “object adapter” pattern, but there also exists a “class adapter” pattern where the adapter inherits the interfaces of both the “expected” interface and the adaptee.

Composite – this pattern allows us to build structures of objects in the form of trees that contain both the objects and compositions of objects. We can apply the same operations over both the composites and the individual objects – the example given in Head First Design Patterns is of a print() operation – we can apply this to any node in the tree to print it in whole or in part.

UML for composite pattern
From wikipedia

Decorator – this pattern allows new responsibilities to be added to an object dynamically – it is “decorated” with the additional responsibility. Decorator class methods must have the same signature of the decorated component but may have different behaviour.

UML for Decorator pattern
From wikipedia

Facade – this pattern provides a unified interface to a set of interfaces in a subsystem. The Gang of Four give the example of a compiler – which may have a simple compile() interface method as opposed to exposing the complex series of commands needed to compile some code.

Proxy – this pattern provides an object as a surrogate for another object to allow control over access to the proxied object. The example the gang of four use is for a graphical object in a document, but these days a webpage may be a better example – for instance I have set the browser on one of my machines not to automatically load Flash. Instead I get a component I can click on to load the Flash if I wish (this means I am not flooded with the advertisers’ web bloat) – sound pretty much like a proxy pattern to me!

UML for proxy pattern
From WikipediaFrom Wikipedia

Bridge  – this pattern places the implementation and the abstraction in two separate hierarchies and allows the two to vary independently.

Bridge UML
From Wikipedia


Maybe my kids should worry about 2009 BD – but I won’t


A color photograph of the Earth and Moon on De...
Image via Wikipedia

Today is my eldest daughter’s 16th birthday. That means in April 2078 she will be a sprightly 82. I will, though, I am sure, be long gone at 112.

And, maybe she should be worried about 2009 BD, the 10 metre lump of rock that passes inside the Moon’s orbit this week – because on 29 April 2078 it is predicted to come very much closer – a mere 6000km or so.

And, then, in August 2087, when Eibhlin will be  92, it will come much closer still – about 2000km.

Of course these predictions are difficult to call accurate – as 2009 BD is so small and so close to both the Earth and Moon that its orbit is bound to be unstable. Eventually it is likely to collide with one of the two or be flung into a new orbit.

But perhaps that collision will come towards the end of this century. If it does it would not be a good idea to be under the rock – but on the other hand while the 7 kT (NASA’s JPL seems to have revised down its estimate from an earlier 18 kT) equivalent of TNT does bear comparison with a nuclear weapon it is a small one and one that would be “exploding” in the upper atmosphere most likely over an ocean.

End of the world watch


Chart of detected NEO's
Image via Wikipedia

My article on 2009 BD, the small rock which makes a near-Earth approach this week continues to be the most popular article on the site – because there are a lot of people out there searching for information about how the world is due to end in June 2011.

It’s not.

It won’t happen.

Nor will 2009 BD crash into us. In fact it won’t even come close enough to be seen without some pretty powerful telescopes.

Creational patterns


The Gang of Four list the following creational patterns:

Abstract Factory – an interface for creating families of related or dependent objects without specifying their concrete classes – the example the Gang of Four give is of an abstract factory that produces “abstract widgets” (ie display artefacts) that can then be subclassed to the particular look and feel of the display (the book shows its age by referring to Motif and Presentation Manager as choices, but the principle is unaltered). This pattern can be used when a system should be independent of how its products are created and represented, or when a library of software objects is needed but one wishes only to expose the interface and not the implementation.

Abstract Factories have a certain inflexibility though – to add a new output object it is necessary to change the interface and that also means changing all the concrete subclasses, as they have to match the interface of their abstract parent.

Builder – this separates the construction of a complex object from its representation, so allowing one construction process to create many different representations.

Builder software pattern
From wikipedia

Factory – defines an interface for creating an object but lets subclasses decide which class to instantiate.

Factory pattern in UML
From wikipedia

Prototype creates a prototypical instance and new objects are instantiated by copying this prototype.

The Gang of Four give an example of a musical score editor, which might create graphic elements to add to the score – but instead of the editor needing to have a subclass for every type of musical object to be added, it calls a parameterised clone method on a graphic (abstract) class that creates a copy of the concrete element sought.

UML for prototype pattern
From wikipedia

Singleton – a pattern to ensure that there is only one instance of a given class and that there is a universal point of access to it.

Often implemented using static methods in the real world:

class Spooler {
private spooler = 0
static Spooler getSpooler() {
if (spooler == 0)
spooler = new Spooler()
return spooler
}
protected Spooler() {
…some initialisation code…..
}
}

The “Gang of Four” software patterns


Cover of "Design Patterns: Elements of Re...
Cover via Amazon

Not about software development in the People’s Republic of China after the end of the Cultural Revolution: this “Gang of Four” are Erich Gamma, Richard Helm, Ralph Johnson and John M. Vlassides, the authors of what many (I have not read it) regard as a classic of computer books – Design patterns : elements of reusable object-oriented software.

Their book is partly a catalogue of design patterns and it is this aspect I am concerned with here.

They divided patterns into three types:

  • Creational: concerned with object instantiation
  • Structural: The composition and organisation of objects into larger structures
  • Behavioural: Algorithms, interactions and control flow between objects