December 28, 2006

Simple and useful Java syntax that you might not know

Nat Pryce introduced me to a bit of Java syntax that is simple, useful and suprisingly little used or known.

It was a suprise to find this syntax after so long - I've been writing Java on-and-off for 10 years - it isn't new syntax and I've pair-programmed with people who have written more Java than me who didn't use this syntax - I don't know why it isn't used much more frequently.

The syntax

Consider this code:

		ArrayList<String> list = new ArrayList<String>();
		list.add("hello");
		list.add("world");

using the syntax that Nat showed me, can be written as:

		ArrayList<String> list = new ArrayList<String>(){{
			add("hello");
			add("world");
		}};

which is neater, particularly if it's a field declaration with assignment.

Any talk of neat syntax must mention Smalltalk

The language which I think has the neatest syntax of any I've used commercially is Smalltalk - it's lovely. In Smalltalk, there is a syntactic construct called "cascading messages" which is similar but more general. The Java syntax above calls the "add" methods on the newly created ArrayList. You can't send multiple messages to the same receiver in the general case, just on construction. For example:

		ArrayList<String> list = new ArrayList<String>();
		list{{
			add("hello");
			add("world");
		}};

is not legal.

Keep it simple

In lots of cases, I avoid using language features or syntax that is unusual. However, in this case, I think this syntax is easy to understand and deserves to be more commonly used.

And finally

Sponsor me for the National Autistic Society's London to Paris Bike Ride. OK - so it's not relevant to the article, but they've been very good to me and my autistic son, and my fundraising could do with a boost.

Posted by ivan at 5:18 PM Copyright (c) 2004-2008 Ivan Moore | Comments (9)

December 12, 2006

Url logger server - simple logging from multiple servers and languages.

Ever spent ten minutes or more trying to find where some logging is going to? Ever wanted a simple way to log from multiple processes or servers? Today my pair and I were having a bad logging day, and having had bad logging days before, I thought I'd do something about it. I wrote a simple http server (based on a previous article) that logs whatever you hit the web server with (here I'm calling it the "url logger server").

Url logger server

The url logger server makes logging for debugging purposes simple. It's not meant for "proper" logging, but as a simple and quick way to add logging for debugging for things where it's difficult to get access to files (or just to work out where they end up!) or where there are a variety of places you want to put logging (e.g. several different servers, processes or code in multiple languages). Please let me know if there's something that already does this. My pair and I found the url logger server useful for our purposes, so I've published it here for others (with permission from my lovely client).

Example use of the url logger server

This is how you log to the url logger server from Java. Most languages can do the equivalent quite easily. In this example I'm running the url logger server on the same machine that this code is running on, but there's no need - it could be anywhere on the network.

	private void someMethod() {
		log("this is a log message");
	}

	private void log(String message) {
		try {
			new URL("http://localhost:8010/log/"+URLEncoder.encode(message)).getContent();
		} catch (MalformedURLException e) {
		} catch (IOException e) {
		}
	}

Viewing the log

In the example above, a browser pointed at "http://localhost:8010/" will show:

this is a log message

Hitting "http://localhost:8010/clear" will clear the log.

The url logger server code

This can be run by jython or python.

import BaseHTTPServer, urllib, os.path

class DBHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def append(self, message):
        f=open('log','a')
        f.write(urllib.unquote(message).replace('+',' ')+'\n')
        f.close()
        
    def clear(self):
        open('log','w').close()
        
    def read(self):
        if not os.path.exists('log'):
            return ""
        return open('log').read()
        
    def do_GET(self):
        path = urllib.unquote(self.path[1:]).split('/')
        
        self.send_response(200)
        self.send_header("Content-type", "text/html") 
        self.end_headers() 
        
        if path[0] == 'log':
            self.append('/'.join(path[1:]))
        else:
            if path[0] == 'clear':
                self.clear()
            else:
                html = "<html><head></head><body><pre>"
                html = html + self.read()
                html = html + "< /pre></body></html>"
                self.wfile.write(html)

server_address = ('', 8010)
httpd = BaseHTTPServer.HTTPServer(server_address, DBHandler)
httpd.serve_forever()
Posted by ivan at 10:18 PM Copyright (c) 2004-2008 Ivan Moore | Comments (1)

December 7, 2006

PoMoPro - the first international conference on postmodern programming

I ran a conference a couple of weekends ago - PoMoPro - the first international conference on postmodern programming. When I say "ran", what I mean is hired Andy Moorley to do the vast majority of the work. Nevertheless, it's still taken enough of my copious spare time to keep me from blogging or doing anything else work-related outside of work time. James Noble and Robert Biddle gave the keynote and Nat Pryce and I ran scrapheap challenge.

Postmodern programming

Lots of software is already written and can solve your problems, if you can only get it to do what you need. Postmodern programming is about using code that already exists, and not writing much code yourself. This is usually in the form of gluing together or configuring other people's code. This is the reality of "enterprise" software today. Postmodern programmers recognise this fact and work with it rather than pretend that it isn't the case and come up with, for example, a programming language or paradigm that would solve all programming problems once and for all if only everybody does everything properly - that way - the one true way. There is no "one true way".

The conference

The aim of the conference is for attendees to learn stuff that they can really use. There will be more hands on programming than most conferences. It's neither academic nor vendor specific. It's not language or technology specific. The keynote speech will be entertaining and thought provoking. The workshop will involve real work and learning.

How it went

From my point of view, I really enjoyed it. James Noble and Robert Biddle were entertaining and thought provoking as expected. The challenges seemed to be the right level of difficulty. For each challenge about half the participants got an acceptable solution. I think the participants enjoyed it and learnt something - at least that's what many said :-)

Other observations

I noticed more participants than in previous scrapheap challenges not really answering the challenge question - doing interesting stuff, but not what Nat and I asked for. Maybe it was because the number of participants was larger than previously, so there was less time per participant from me and Nat to explain what we wanted once the challenge had started.

I had the impression that pairs who split the work between them and then tried to integrate what they had done didn't do any better, and in many cases worse, than those pairs who worked on one laptop and didn't try to divide the work up between them. I also thought that those who split the work up weren't having as much fun. Comments from attendees are most welcome - these are quite subjective "observations".

Future scrapheap challenges

Nat and I are running scrapheap challenge again at SPA. I don't know when, or if, the second international conference on postmodern programming will be held.

Posted by ivan at 8:43 PM Copyright (c) 2004-2008 Ivan Moore