Springer and Scala


I need to learn the Scala programming language. Unfortunately the University of York’s library does not seem to have an electronic copy of “Programming in Scala” (Amazon link) but it did have an electronic copy of  Springer’s “A Beginner’s Guide to Scala” (Amazon link). But this is a very poor book, referring back to examples that don’t exist, offering a very confusing explanation as to what object-orientation is and, to cap it all, illustrating examples with pseudo code rather than Scala itself.

Of course, it’s not the worst example you’ll find from Springer – “Unleash the System on Chip using FPGAs…” is easily the worst book I have ever seen in print (see my review on Amazon here) – and, of course they also publish many useful books and conference proceedings and so on. But they appear to have close to a monopoly on many aspects of computer science publications and use that ruthlessly.

If it wasn’t for other factors I’d suggest the European Commission needs to take a close look at them. Hardly worth it in the UK’s case these days though.

Jobs, jobs, jobs


.Net Framework Logo
Image via Wikipedia

My post on the HESA longitudinal survey of graduates made it on to slashdot and provoked a healthy discussion here.

Lots of people complaining that what universities call “computer science” is not computer science at all – not enough maths or rigour or theory in general.

That may or may not be true: I am not an undergraduate, so cannot comment. But I do know from my experience of the MSc that you can make of it what you will.

A lot of people on the course complained that the object-orientated programming and design part was in Groovy and not Java (or, heaven forfend, some .NET flavour). Unlike me they worked in IT and saw the course as a step up the career ladder – I saw it more as a mind expansion thing (though also was about proving to employers that my claim of IT skills was real). The more I read – especially when I got into Structure and Interpretation of Computer Programs – the more I could see what the lecturers were on about.

I don’t think one position was superior to the other and I certainly don’t think teaching Java instead of Groovy would have harmed anyone’s employment chances – so the argument that people teach useless task-orientated stuff and not enough science does not work for me in explaining high levels of unemployment.

Men and boys who are poorly socialised strikes me as a better explanation, but again I am not backing that with any evidence!

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

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


GRASP software patterns


This is a UML diagram (created in IBM Rhapsody...
Image via Wikipedia

My final exam is on Tuesday and covers object-orientated design and programming – hence the Groovy Game of Life code.

Software patterns are a big part of the course and part of that is the simple task of remembering what each pattern does. I have found Head First Design Patterns useful but it covers few patterns and certainly not the basic GRASP ones, that I do have to know.

GRASP stands for General Responsibility Assignment Software Patterns (or Principles – I actually think this comes closer to expressing what this is all about anyway).

These are:

Information Expert, solving the problem of the general principle of assigning responsibilities to objects by assigning the responsibilities to the information expert – the class that has the information necessary to fulfil the responsibility.

Creator, solving the problem of what should be responsible for creating a new instance of some class by assigning the responsibility of creating a new instance of class A  to the class, B, that:

  • aggregates A objects; or
  • contains A objects; or
  • records instances of A objects; or
  • closely uses A objects; or
  • has the initialising data that will be passed to A when it is created.

(If more than one class displays these characteristics then aggregation or composition should be preferred.)

Low Coupling, solving the problem of creating classes that have low levels of dependency and face a low impact when other classes are changed and can be more easily reused by assigning responsibilities so that coupling remains low.

Controller, which addresses the question of what should be responsible for handling an input system event by assigning the responsibility to a class that represents one of the following choices:

  • It represents the overall system, device or subsystem (it is a facade controller); or
  • It represents a use case scenario within which the system event occurs, often named Handler or Coordinator, etc (it is a use-case or session controller).

High Cohesion, which addresses the problem of how to keep complexity manageable and how to keep objects focused by assigning responsibilities so that cohesion remains high.