Archive for the 'Programming' Category


Eclipse Debugger Gripes

Sunday, July 9th, 2006

Since I switched to using Eclipse for my Java developer I also switched to use its built in debugger. In the past I’ve used JSwat, which is a great open source Java debugger, but I’ve had some troubles with recent versions with getting it to pick up my source path. This made the switch easier.

Having your debugger integrated with your editor is great, but so far I haven’t played with hotswapping. I’m debugging everything in isolation with JUnit, which makes tracking down bugs a lot quicker.

But this article is called ‘Eclipse Debugger Gripes’, so here are the moans: ;)

Variable Names DisappearNo variable names in Eclipse Debugger

Every so often, normally as I’m just about to track down a tricky bug, all the variable name information disappears. See the screen shot to see what I’m talking about. You can see the variable values, but you don’t know what the value is for. The only way to fix this is to restart Eclipse. Easy fix but annoying.

At first I thought it was the Sun JVM not playing nice with IBM’s IDE, so I switched to their JVM. Initially it seemed better, but every now and again the names disappear. I have no idea what this is the case, but it’s very annoying.

Jad

This isn’t a gripe about Eclipse so much but JadClipse. It has the option to synchronize the lines of the decompiled file with the line information in the class. This allows you to set breakpoints in binaries. Very useful, but doesn’t always work, sometimes it just doesn’t sync them up. This is where the problem with Eclipse comes in, it only allows you to set a breakpoint by highlighting the line in editor that contains the source, you can’t set one manually. So if Jad can’t create a source file where the lines don’t match up, I can’t set a breakpoint.

Source Paths

I came across this one when Jad wouldn’t do its thing. You can assign a source path to each library you import. But this only takes affect after you restart Eclipse. I thought it was broken and almost started tearing out my hair when it wouldn’t stop bringing up the incorrect decompiled source. A restart corrected this. I’m including this one to save others of this grief.

Otherwise, if you’re using Eclipse and haven’t already, I highly recommend you give the debugger a go.

Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit Eclipse Debugger Gripes digg.com digg it!  |  reddit reddit!

New Language

Saturday, July 8th, 2006

I’ve been wondering what language to learn next for a while. Scala caught my eye. I really should spend more time with Ruby since Rails programming hasn’t taught me much about the dynamic aspects of the language, which is what makes it interesting. I also want to pick up Scheme at some point. So what language did I go for? Prolog.

Not the most practical language in the world, but it’s one of those languages I liked at university but haven’t played with since. It’s not the most popular language either, in fact I think they’ve dropped the advanced Prolog course from the Computing degree at Imperial, which is a shame.

Clause and Effect: Prolog Programming for the Working Programmer

Since I’ve done some Prolog programming before I avoided a beginner’s tutorial and went for Clause and Effect: Prolog Programming for the Working Programmer, which is a terse introduction and series of exercises. I’ve worked through the first two chapters, which is a refresher on lists and backtracking, and remember why I like it so much. You just state what the program is supposed to be rather than how it’s supposed to do it. I remember going from the Prolog labs to Java programming and getting annoyed that just writing a pre and post condition wasn’t enough, you actually had to manipulate your data.

I’m not sure how learning Prolog again will improve my programming, but I’m certain it will, at very least it’ll make me consider backtracking as another form of control flow.

On a slight tangent, IBM DeveloperWorks has an interesting article on how you can use continuations in Scheme to implement Prolog style backtracking. They also show how to implement Python’s generators and Java’s exceptions. I really must learn Scheme so I can understand it. ;)

Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit New Language digg.com digg it!  |  reddit reddit!

icalendar and Rails

Monday, June 26th, 2006

I’ve recently used icalendar to output an ical from a Rails app I’m running. It’s incredibly simple, here’s what I did:

  1. Create an ical_controller:
    script/generate controller ical
  2. Add a method to generates the events:
    require 'icalendar'
    
    class IcalController < ApplicationController
    
      caches_page :competitions
    
      def competitions
        @cal = Icalendar::Calendar.new
    
        Competition.find_all.each do |comp|
          event = Icalendar::Event.new
          event.start = comp.date
          event.end = comp.date
          event.summary = comp.name
    
          @cal.add event
        end
      end
    
    end
  3. Create a view (app/views/ical/competitions.rhtml):
    < %= @cal.to_ical %>
  4. Install icalendar into your vendor directory:
    cd vendor
    gem unpack icalendar
  5. Add the necessary dependency to config/environment.rb
    require 'icalendar-0.96.4/lib/icalendar'

And that’s it. Once deployed you can access your ical and import it anywhere. I’ve tried mine out with Google Calendar and it imported without a hitch. One deficiency in icalendar is the inability to give a name or description to the calendar itself, so you’ll have to rename it in your calendar application. The only caveat in the above code is the caching directive in the controller. I’ve cached the entire page because the events don’t change frequently. To expire the cache you’ll have to add the following line to the appropriate controller methods where your events changes:

expire_page :controller => "ical", :action => "competitions"
Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit icalendar and Rails digg.com digg it!  |  reddit reddit!

Scala Might Have Legs

Saturday, June 17th, 2006

It looks like Scala is creeping into the mainstream. I definitely have to try it out on something ‘real’ soon. In the meantime here are some posts I’ve come across introducing Scala:

Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit Scala Might Have Legs digg.com digg it!  |  reddit reddit!

Software project late again?

Saturday, June 17th, 2006

This post brought a smile to my face. Sound familiar? ;)

Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit Software project late again? digg.com digg it!  |  reddit reddit!

Why do default implementations have such bad names?

Saturday, June 17th, 2006

Small rant about class names in Java, or more specifically classes who are the sole implementation of a particular interface. You go to the effort of coming up with a good name for your interface, e.g. IndexSearcher, but then the class name is enevitably one of:

  • SimpleIndexSearcher
  • IndexSearcherImpl

I’m guilty of this. There must be a better way to name our classes!?!

Don’t forget the other pattern, if IndexSearcher is your class, then IIndexSearcher is your interface. I hate that one too. :)

Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit Why do default implementations have such bad names? digg.com digg it!  |  reddit reddit!

Mock Objects and Testing Controllers

Saturday, June 17th, 2006

Up to now I assumed mock objects were just dummy objects you used in your unit tests when you didn’t want to use a real object, e.g. because the real object goes off and does something weird to a remote server. But apparently Mocks Aren’t Stubs, they are objects that allow you to do a different style of testing. Most units tests involve verifying the correct state of an object after an interaction, with mocks you can make sure the right methods are being called in the first place (see Martin Fowler’s article for more).

Most of the time I wouldn’t want to test the interaction, I just want to test an object, so mocks aren’t needed, but one area of my programming that always falls short of testing is controllers (in the MVC sense). They just require too many bits and pieces to get running that you eventually end up running your entire program for one test. Then I came across a couple of posts from Robert Chatley, who was in the same research group as me at university. He talks about using Spring’s mocks, as well as using JMock. That’s pretty much what I wanted to do and it all looked very easy.

Imagine we have a controller that does a Lucene search, we want to make sure it’s actually doing the search, here’s an example test case using JMock:

public SearchControllerTest extends MockObjectTestCase {
    private Mock searcher;
    private Mock logger;
    private SearchController controller;

    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    public void setUp() {
        super.setUp();

        this.mockSearcher = mock(IndexSearcher.class);
        this.mockLogger = mock(QueryLogger.class);

        this.request = new MockHttpServletRequest();
        this.response = new MockHttpServletResponse();
        this.request.setMethod(“GET”);

        this.controller = new SearchController();
        this.controller.setSearcher((IndexSearcher) searcher.proxy());
        this.controller.setQueryLogger(logger.proxy());
    }

    public void testSearch() {
        // Set our search term
        this.request.setParameter(“q”, “apples”);

        // Set our expectations
        Mock mockHits = mock(Hits.class);
        mockHits.stubs().method(“length”).will(returnValue(10));

        this.mockSearcher.expects(once()).method(“search”).will(returnValue(hits));

        // Do the request
        ModelAndView modelAndView = this.controller.handleRequest(this.request,
                                                                  this.response);

        // Verify our hits are stored in the model
        Map model = modelAndView.getModel();
        assertEquals(model.get(“hits”, mockHits.proxy());
    }

    public void testSearchWithNoResults() {
        // Set our search term
        this.request.setParameter(“q”, “apples”);

        // Set our expectations
        Mock mockHits = mock(Hits.class);
        mockHits.stubs().method(“length”).will(returnValue(0)); // We have an empty hits object

        // We’re not checking this time, just providing a stub to return our
        // hits object
        this.mockSearcher.stubs().method(“search”).will(returnValue(hits));

        // Because we have no results, we expect this query to be logged.
        this.mockLogger.expects(once()).method(“noHits”);

        // Do the request
        ModelAndView modelAndView = this.controller.handleRequest(this.request,
                                                                  this.response);
    }

}

In the above example we have two test cases, the first checks a search is executed correctly, and the second checks a special case where we log the query if it returns no results. We setup several mock objects, and for each one you have to state what calls you expect to be made on it, and what (if any) return value should be given.

There are two ways to get a mock to respond to a method, either with expects() or stubs(). Use expects if you want to test the method call. You’ll have to specify none(), once() or atLeastOnce(). Use stubs if you just want it to return a value, e.g. the length of our Hits object.

One nice thing about JMock is that the tests are sentence like, it’s very easy to read and understand what a line is doing, e.g. the searcher expects the method ’search’ to be called once. One (major) problem with JMock is the completely barren Javadocs. There is no documentation for the MockObjectTestCase class. This makes it pretty hard to write a test unless you’re copying someone else’s example.

This above example is very simple, but it’s possible to test error conditions, page flow and various other niggly bits of controllers, which means we can be confident of their behaviour and no longer have to ‘run and pray’.

Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit Mock Objects and Testing Controllers digg.com digg it!  |  reddit reddit!

Someone is using Haskell…

Wednesday, May 31st, 2006

It looks like the guys at Linspire (formally Lindows) are using Haskell as their main language for OS development:

At Linspire, our choices have been OCaml and Haskell. David Fox wrote the hardware detector in OCaml and is now porting it to Haskell. Jeremy Shaw has been doing various utilities in Haskell for several years. Sean Meiners recently wrote an application for managing his recipe collection and is now hooked. I am porting our CD build procedure from OCaml to Haskell.

I wonder if this is the start of a renaissance period for functional languages. ;)

Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit Someone is using Haskell… digg.com digg it!  |  reddit reddit!

Functional Languages and Scala

Tuesday, May 16th, 2006

For a while now I’ve been thinking about learning a functional language (XSLT excluded). I was always fond of Haskell at university, but it seems to be an academic language without many ‘real world’ uses. The other obvious choice would be Common Lisp, but the syntax really puts me off. Another one that caught my eye is Erlang because I’m doing some distributed programming at the moment, but the only book on Amazon costs 50 quid, which dampened my interest.

Today I came across a language called Scala. Strictly speaking it isn’t a functional language, it’s a hybrid of OO and functional.

Scala is object-oriented
Scala is a pure object-oriented language in the sense that every value is an object. Types and behavior of objects are described by classes and traits. Class abstractions are extended by subclassing and a flexible mixin-based composition mechanism as a clean replacement for multiple inheritance.
Scala is functional
Scala is also a functional language in the sense that every function is a value. Scala provides a lightweight syntax for defining anonymous functions, it supports higher-order functions, it allows functions to be nested, and supports currying. Scala’s case classes and its built-in support for pattern matching model algebraic types used in many functional programming languages.

But a lot of these features also exist in Ruby, another language I’ve been playing with. So why does Scala peak my interest? It runs on the JVM and can use all the existing Java class libraries. This means I could use it on my projects at work, i.e. something reasonable complex. The most I’ve pushed Ruby is to do some processing for a web site, hardly rocket science, and it’s foreign enough I couldn’t just start using it at work.

A JVM compatible language with higher order functions, mixins, operator overloading, built-in XML processing…I don’t think I’ve been this excited by a programming language for quite some time. ;)

Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit Functional Languages and Scala digg.com digg it!  |  reddit reddit!

More Rails on DreamHost Pain

Sunday, May 14th, 2006

I thought I sorted out my problems with my sites needing Rails 1.0 by configuring them to use specific versions of the required gems. But this was short lived, the other day my sites just stopped working. I reported the problem to DreamHost and after a couple days they told me I was trying to use a version of a gem that wasn’t available. The various gems and the versions needed are:

rails 1.0.0 1.1.0
activerecord 1.13.2 1.14.0
actionpack 1.11.2 1.12.0
actionmailer 1.1.5 1.2.0
activesupport 1.2.5 1.3.0
actionwebservice 1.0.0 1.1.0

I had setup my environment.rb file to lock the gems to the versions needed for Rails 1.0.0, this got around the problems with the Rails 1.1 upgrade. So what went wrong? DreamHost uninstalled activerecord 1.13.2, 1.14.0 doesn’t work with Rails 1.0. “Aha!” I hear a lot of you say, “you should have run rake freezegems“, which is in fact what I did to get everything working again, but I do have an issue with it. By running freezegems you’re copying the libraries into your application, so for each app you need a complete copy of Rails. That’s a pretty old school way of doing things, we’ve had shared libraries for a long time now.

But space is not my major concern, my first one is minor bug fixes. If there’s a bug, or more likely a security issue, there should be a compatible version of the library released with the fix. This minor upgrade should continue working with my application without me doing anything, if you copy the library into your app you don’t get this benefit. The other issue is that by copying Rails into your application it doesn’t matter if your host has Rails installed since you’re using your own copy. All those gems that DreamHost installs? Absolutely useless. I install them on my laptop, do a rake freezegems and copy the whole lot over. On a related note by uninstalling activerecord 1.13.2 I couldn’t have done freezegems on the host, I had to do it locally.

This is such an unsustainable (I could say ‘doesn’t scale’ but I know how bothered people get with that phrase ;) ) way of managing libraries. Sure it’s fine for my two applications, but what happens if you have ten, or a hundred? Each time a new version of a gem is released you need to go to each one of them and do a ‘rake freeze_gems’. If your host doesn’t install the complete set of versions you need, then you need to do it somewhere else and copy everything over, madness!

Spread the word: Technorati related  |  del.icio.us bookmark it!  |  submit More Rails on DreamHost Pain digg.com digg it!  |  reddit reddit!