And This is Charles's Fault

2 PM May 30, 2003
Via IM...
Alan:    Which begs the question, "If it's embedded 
         inside another page, how can the JSP I am 
         writing have a <head>?"
Charles: Off with its <head>.
Alan:    No. It would confuse every<body>.
Charles: Just remember.
Charles: Every <body> wants some</body> to lean on.
By alang | # | Comments (0)
(Posted to Software Development)

Tips For Using Java booleans

12 AM May 30, 2003

The full implications of the concept of a boolean value eludes many novice Java programmers. Perhaps this is because some other languages1 have expressions with boolean results, but cannot store these in results in variables or parameters.

For instance, just today I came across an if statement like this:

    if (oneObject.isFlagSet() == true) {
        anotherObject.setFlagX(true);
        anotherObject.setFlagY(true);
    } else {
        anotherObject.setFlagX(false);
        anotherObject.setFlagY(false);
    }

It took a few seconds for the precise meaning to sink in. First, consider that the if statement’s condition expression3 must be a boolean. For this reason, a program will often use an operator that produces a boolean result, such as ==, like this:

    if (a == b) {
        ...

In our case, oneObject.isFlagSet() already is a boolean, so there is no need to compare it to another value. Explicitly comparing it to true is at best useless, and at worst confusing. It would be better to write:

    if (oneObject.isFlagSet()) {
        ...

Next, consider the body of the if and else clauses. When executing the ‘if’ part, the condition (oneObject.isFlagSet()) must be true, and when executing the ‘else’ part, it must be false. We can therefore4 re-write the original if statement as:

    anotherObject.setFlagX(oneObject.isFlagSet());
    anotherObject.setFlagY(oneObject.isFlagSet());

Hey Presto! Seven lines of code into two, and the result is arguably more readable, understandable and maintainable.

Please pass this tip on to anyone that would benefit from it.

1 COBOL and SQL spring to mind here.

2 C, (older versions of) C++ and (older versions of) Python do not have a boolean type, though they can treat other variable values as booleans.

3 The bit in the brackets after the if.

4 Assuming that calling oneObject.isFlagSet() has no side-effects.

By alang | # | Comments (0)
(Posted to Software Development)

Most Egregious Use Of Modern Dance in an e-Commerce Context

1 PM May 29, 2003

And the award for Most Egregious Use Of Modern Dance in an e-Commerce Context goes to Trolltech for their webshop page.

By alang | # | Comments (0)
(Posted to Stuff)

Psyco - Python, only Twice As Fast

6 PM May 25, 2003

Psyco is a JIT-like compiler for Python. It has been under development for sometime, and earlier this month made it to version 1.0.

I downloaded it and timed it over a couple of simple programs. The test programs were similar to this one, having a mix of list and string manipulation.

To use psyco in my scripts I added just two lines to the top of each file:

    import psyco
    psyco.full()

On average, I saw just under a doubling in speed. For different tasks, times went from 48 seconds down to 25, from 41 to 22 and 17.2 to 9.3. Quite impressive considering the small effort I put in, and that Psyco’s strengths are more in the area of arithmetic than list manipulation.

As with any such product, I would want to investigate Psyco’s stability, profiling features and memory usage more closely before using it in a larger application. On the other hand, maybe it’s not such a big risk – if I discovered adverse side-effects, I could just turn it off.

By alang | # | Comments (1)
(Posted to Software Development)

And another thing wrong with J2EE...

1 PM May 23, 2003

Found this paper, by Robin Sharp, at Software Reality. It goes into some detail about the current state of Java. In particular, the non-OO-ness of J2EE. I found it to be quite complementary to Marc Fleury’s Why I Love EJB‘s.

Both papers acknowledge that the J2EE spec evolves, not with real world experience, but with the bleeding-edge, theoretical wonderings of the industry techno-vangelists and conference speakers. Both Robin and Marc go on to provide alternate solutions, though Marc has stayed more main-stream than Robin.

By alang | # | Comments (0)
(Posted to Software Development)

Proud To Program

9 PM May 22, 2003

There’s something satisfying about shipping a well-written class fronted with an elegant interface. Makes me proud. It’s a pity code is electronic, otherwise I could wrap our library in a tasteful recycled paper, tied with an understated ribbon and sporting a small card that says:

Here at [insert organisation], we are proud of our coding products. Our developers use only the purest 7-bit ASCII characters, typed by hand, arranged in compliance with the Java Language Specification and checked with a modern compiler. We hope you enjoy programming with this class.

By alang | # | Comments (0)
(Posted to Software Development)

Free Beer Offer: The Results

12 AM May 22, 2003

OK, so I was brave and offered the world a free beer in exchange for being sociable. It turned out to be a short, sharp lesson in how small the world is. There were three takers:

  • Mike Cannon-Brookes from Atlassian. Charles and I went and met Mike, Scott and the gang at their new(-ish) offices. They have a world map on which they place a dot for each JIRA sale, and the world is going dotty. Turns out that I had already met Mike—his brother in law, Andrew, is a close friend, and Mike’s niece is my god-daughter.
  • Daniel Bradby—of Hibernate Eclipse plugin fame. Daniel actually works in the Melbourne office of the same company that I work for, but he saw my offer on the blog so I’m counting him in.
  • Oliver Burn, who is the person most responsible for Checkstyle. Oliver and I almost worked together at one of my previous employers. He left six months before I joined. Oliver and I met with Malcolm Edgar, who had also worked at the same place.

Topics of conversation varied from compiling Java in a pub with an iPod and two Apple PowerBooks, through to how the Collins class submarine’s project schedule was managed. Also talked about enterprise architectures, Python and web services. Learnt a lot, made and renewed acquaintances, had a lot of fun. Must put out the offer again in a few months time—maybe I’ll even meet someone I don’t already know.

Postscript: Karen (my wife) mentioned all this activity to our friend James on the weekend. He said, “Oh, that was you?”. James had been travelling in the great Aussie outback over the last few weeks. While passing through Tenterfield he heard a story about some guy who was offering “free beer and a chat” on the radio. No doubt TripleJ paid their usual great amount of respect to the subject. If anybody can confirm this little story or add more detail, I’d be grateful.

By alang | # | Comments (0)
(Posted to Software Development)

My Mum Has a Website

12 AM May 21, 2003

My Mum and her husband made a site all about their retirement farm. It’s all there: the good, the bad and the ugly. There are a few good pictures too.

PS: Nice story about the trailer Mum!

By alang | # | Comments (0)
(Posted to Stuff)

Python/ZSI and Python for Java Programmers

11 PM May 20, 2003

Wrote and presented on two topics over the last few weeks. Here are the slides for posterity:

By alang | # | Comments (0)
(Posted to Software Development)

Sun Web Services Tutorial Bugs + Hacks

12 AM May 16, 2003

Started on the The Java Web Services Tutorial just tonight. It is a pretty comprehensive guide to the Java Web Services Developer Pack 1.1. A dauntingly large body of technology, the WSDP ships with over 90(!) JAR files.

Diving into the tutorial, you first have to get Tomcat running. Chapter 3 Getting Started with Tomcat guides you through this process by compiling and deploying a tiny application consisting of a single JavaBean and a single JSP. Everything worked fine up to the final step, “ant install”.

At this point I got a FileNotFoundException. Half hour or so of reading the build.xml file and the ant documentation (I am an ant newbie), and I figure out that it means I need to define two properties on the ant command line: “ant -Dusername=blah -Dpassword=blah install”. I’m sure the tutorial could have told me about that. And FileNotFoundException?

With that behind me, it’s on to Chapter 11, Building Web Services With JAX-RPC. Again, everything worked fine up to the final step, “ant run”, which kicks off the client application. Boom!

Exception in thread “main” java.lang.NoClassDefFoundError: javax.xml.transform.Source

After working out what a javax.xml.transform.Source was—thanks Google—I finally traced it back to the build.properties file. Sun had misspelt “jaxp.home” as “jaxp.holme”. Grrrr.

OK, try again. “ant run”. Boom!

Exception in thread “main” java.lang.NoClassDefFoundError: com/sun/net/ssl/HostnameVerifier

Back to Google again. This time it turned out that jsse.jar (whatever that is) was missing from the classpath. A little stuffing around with the unix find command, a little ant debugging with <echo> and it became clear I needed to add ”:${wlib}/jsse.jar” to the end of the wjars variable.

Try again. “ant run”. Success. My computer tells me:

Hello Duke!

So right now I’m pretty happy that I was able to get my computer to say hello to me after only three hours of effort. Pretty happy, even though my name isn’t Duke.

PS: I fired off an email to jwsdp-feedback@sun.com.

By alang | # | Comments (6)
(Posted to Software Development)

Static/Dynamic Typing and Productivity

7 AM May 15, 2003

Dave pointed me to his writings on the topic of Static vs. Dynamic. In true Internet debating style, let me just address one of his points for the time being:

Python, PERL, and other scripting languages have features outside of weak typing that make them easy to program in. PERL‘s list manipulation, terse syntax, and regular expression handling are a huge part of the appeal. If you add strong typing to PERL, you really don’t lose a whole lot.

I agree that typing is not responsible for the whole productivity increase1 of Perl and Python over Java. But it sure is a lot of it.

I remember when I tried to explain to a bunch of C++ programmers that the main benefit of Java garbage collection is the reduction in memory management logic throughout your program. Initially, the C++ programmers just couldn’t see how much of their design and code dealt with keeping track of who owned which memory and making sure it was released. It was like explaining water to fish.

Similarly, much of a Java program is due to the need to satisfy the compiler. Not only do individual lines of code get longer due to the need to (keyboard) type more2, but the design and existence of whole blocks of code and even entire classes is dictated by the need to satisfy static type checking.

A simple example is anonymous inner classes. A powerful concept, but unfortunately it requires four lines of boilerplate to wrap a single line of code.

As far as what you do differently in a dynamically typed language in order to ensure that you have a correct program… I’m sure that there’s a blog entry there.

1 And when I say productivity increase, I am comparing apples with apples: effort required to get programs running with similar and acceptable levels of defects.

2 I wrote about that here.

By alang | # | Comments (0)
(Posted to Software Development)

Javadoc Comments

12 AM May 15, 2003

I'm currently working on a system that's just huge. Given its size, the number of developers that have worked on it, and the general hurly-burly of development, you expect to find the odd piece that shows evidence of having been developed in a hurry. Even so, this class Javadoc made me smile. I present it complete and unaltered:

/**
 *
 *
 *
 */
By alang | # | Comments (0)
(Posted to Software Development)

Static vs. Dynamic Philosophy and JDK 1.5 Generics

10 PM May 14, 2003

I was going to stay out of the latest Static vs. Dynamic debate. Really I was. But then I read Joshua Bloch’s JDK1.5 interview on Sun’s Java site. It’s a good article, but one thing made my blood boil.

Static-typing supporters often predict catastrophic runtime errors should someone ever write a program in a language without static typing. This, despite plenty of evidence to the contrary from Ruby, Python and Smalltalk developers.

Well Bloch tells us that our statically-typed Java code is not safe from runtime errors. The problem is type safety. Apparently we need more type safety, and we need it in the form of Java generics1. He is quoted:

The upside [of generics] is that if you try to insert something [into a collection of strings] that’s not a string, you find out at compile time and fix the problem. Without generics, you discover such a bug when your most important customer calls your VP to tell him that the program on which his business depends just crashed with a ClassCastException.

Well, Mr Bloch, practically speaking, you discover such a bug long before your customer does. This isn’t a theoretical position I’ve arrived at as a result of a dynamic-typing-philosophy navel gaze. I say it in light of the millions of hours of generic-less Java coding that developers have already done.

From my own experience, and fromwhat I read on forums, the kinds of runtime exceptions that cause VPs grief are: NullPointerExceptions, slightly and subtly misconfigured J2EE servers, and mismatched versions of serialized classes. Even FileNotFound when looking for a vital .properties files, unexpected SqlExceptions and OutOfMemoryErrors are more common than ClassCastExceptions.

In short, it seems that ClassCastExceptions are already weeded out early on in the development process. We don’t need more static typing for better type safety—there are bigger problems to solve.

I’m going to stop here because, if I went on, I’d say something inflamatory like, “Bloch’s statement is typical of programmers that place unthinking faith in static typing as some kind of bug removal panacea.” Then I’d probably repeat a whole bunch of stuff that Bruce Eckel already said more articulately than I ever could. And no doubt I’d not resist the temptation to stir up dissension between the Java Generics and CORBA camps by asking if, now we have generics, EJB Entity Bean finders are going to continue returning Collections that require us to cast each and every member using PortableRemoteObject.narrow.

Yes, best to stop now.

1 I should point out that I think generics are a good idea. They work in well with the strong-static-typing flavour of Java, they make good documentation, and they get rid of the constant casting around we have to do whenever using collections.

By alang | # | Comments (0)
(Posted to Software Development)

Best Game of Jenga Ever!

10 PM May 13, 2003

We played a game of Jenga at Bible study recently, and it turned out simply amazing. The tight, four way competition, the tension rising move by move, the teetering tower, treacherous blocks sticking unexpectedly, and… you get the picture.

Here is a picture from just before it all fell, when we were 13 layers above starting height:

!/pics/blog/001_jenga.jpg (Precarious stack of Jenga blocks)!

Originally the bottom layer was resting on the two outer blocks. I managed to push the whole stack over to rest on just one block—using the regulation single hand—to get hold of a bottom block. I thought I was such a hero.

But shortly after this photo was taken, Michele went and did the same thing from the tenth layer up. She slid one of the outer blocks over to the middle, then took the other block away. All single handed, exactly as per the rules. Michele is the new, all-time Jenga champion. I am not worthy.

Unfortunately, she was a bit too quick putting her newly freed block back on top, and there was the cliched mighty crash.

Ah beautiful, capricious Jenga! The game of no winners and only one loser.

By alang | # | Comments (0)
(Posted to Stuff)

Klingon and Java Coding Standards

5 PM May 12, 2003

After reading this crazy report from CNN, I feel compelled to make the following addition to the corporate coding standards:

Rule 50: Do not use Klingon variable names. This means you.

By alang | # | Comments (0)
(Posted to Software Development)

Microsoft Impresses Our Children

8 AM May 10, 2003

Was just talking to my son, Mitchell, age eight. He was—get this—having a rant about the software on his computer. We often talk about computers, but I’ve never told him how evil Windows is or how to spell M$, or anything like that. So it was completely off his own bat that he came to this conclusion:

“Microsoft Works” should be “Microsoft Doesn’t Works”

I am so proud.

By alang | # | Comments (0)
(Posted to Software Development)

Bruce Eckel: Strong Typing vs. Strong Testing

11 PM May 7, 2003
Bruce Eckel wades into the Static/Dynamic Typing debate once more, with code examples and lots of reasoned opinion...
The benefit of simpler, clearer expression of concepts is simply not worth the danger. Even if that benefit is a productivity increase of 5 to 10 times over that of Java or C++.
By alang | # | Comments (0)
(Posted to Software Development)

Hackfest Ideas

11 PM May 7, 2003

I've been toying with getting together a group of fellow computer-geeks sometime later this year for a Day Of Hacking.

Right now, I'm looking for ideas. The key words are Quick, Cool, Fun and Nerdy. Here are some initial thoughts (the better ideas are from my friends):

  • Pick up a Java workflow framework one of my friends is developing and build something with it.
  • Put together a charity website.
  • Build a simple application from components in ten different languages.
  • Work out the best way to write EJBs in Jython or Kawa.
  • Learn a new language - Scheme, Ruby, CAML, Smalltalk?
  • Write a 2D game in PyGame.
  • Everybody writes a program to the same spec. Every 30 minutes, we all stand up and move one computer to the left.

What do you think? What would you do?

By alang | # | Comments (0)
(Posted to Software Development)

Guide To Free Beer in Sydney

11 PM May 6, 2003

Work with POJOs, EJBs, Python or Web Services? Live in Sydney? Like a beer1 and a chat? If you'd like to meet up one evening to talk about building applications, enterprise architecture or even how much you hate Prevayler (especially if you haven't tried it), then drop me a line - alan.green at cardboard.nu. I'll buy the first round.

A quick scan of Javablogs yields further Sydney-based opportunities to partake of alcoholic beverages in exchange for temporary expression of the social graces:

  • Charles offers free beer if you can find him in the Menzies Hotel at the Wednesday pool-comp.
  • Mike extends a beer or soft-drink as part of a tour of his company's new digs.

Hmmmm. With a bit of planning and foresight, it may be possible to do all three in one night :)

Hope to hear from you soon.

1Or soft-drink, of course.

By alang | # | Comments (0)
(Posted to Software Development)

TDD - Not Software Engineering's Biggest Problem

9 AM May 3, 2003

Les asks: "whether or not the wide adoption of TDD has signaled the end (or at least the failure) of the software engineering discipline as we know it."


I'd argue that Test Driven Design/Development is well enough defined to qualify as a formal method. Like most formal methods, it is based partly on what the method designer thought was a good idea at the time, partly on the experience of its practitioners and partly on the results of concrete, statistical studies. The mix changes over time as the method matures.


If TDD gives you the quality and functionality you need at the right price, then it's the right engineering tool. If, on the other hand, it's used simply as a management hack, the resulting product will reflect that.


For anything where a life depends on it, I'd like to think that there are multiple verfication paths - source code inspections right through to in-situ acceptance testing with very brave test pilots, and everything in between. (I heard somewhere that) Airbus, for instance used to have two teams each implement the specification independently, and then run both during the flight.


I have had some second-hand contact with government systems. Without pointing the finger too precisely, these were systems that wouldn't kill someone immediately, but potentially make life very difficult for individuals and the public when they screwed up. They used waterfall based structured design techniques, whose main purpose was to ensure that the blame was spread evenly and thinly. In the end, it often comes down to the efforts of a lone contractor to get it right.


To be fair to government agencies, you need to read that anecdote in the context of what is typical of IT generally. And software engineering is not, and never has been typical of IT shops.

By alang | # | Comments (0)
(Posted to Software Development)

Java Threading Heuristics

11 PM May 2, 2003

Warning: Introductory rant follows. You may want to skip down three paragraphs.

One of things that got developers excited back in the early days of Java1 was its built in support for threading. This came via java.lang.Thread, the keywords synchronize and synchronized, the (well thought-out but non-intuitive) methods wait() and notify(), and a handful of other features. Sun then made sure that everyone knew how to use these mechanisms properly - through articles, conferences, certification and the venerable Java Tutorial.

However, after a few long debugging sessions recently, I have come to the conclusion that there are quite a number of Java programmers out there who do not have a solid grounding in Java threads2.

In the hope of easing any future pain, and in the hope of making the world a better place, here are the heuristics that I use when building or debugging threaded code.

---END OF RANT---

Heuristic 1: If there is any possibility one thread may read a value that another is changing, you need at least one synchronize or synchronized somewhere.

Rationale: When two threads operate on the same values simultaneously, they often end up doing things that the programmer did not expect. The Java Language Specification discusses some of the surprising kinds of behaviours that can emerge when two threads interact without coordination. There are no atomic operations in Java (e.g. a Test And Set operation) that are useful for coordinating access to values between threads, therefore you need to use synchronize to avoid these surprising behaviours.

Corollary 1a: Even if threads "mostly just read" a value, you still need to use synchronize.

Rationale: "Mostly just read" is another way of say "sometimes writes". Not using synchronize is just asking for your program to fail in the most interesting and unrepeatable ways.

Corollary 1b: Even if you are 100% sure that two threads accessing the same values won't interact unexpectedly because you hand-checked all possible execution paths, use synchronize anyway.

Rationale: There are so many, many ways that two threads can mis-behave in this situation it's better to be safe than sorry. There's also the next programmer to consider - and he may not be as smart as you.

Heuristic 2: The fewer synchronized blocks you have, the less chance there is of introducing a hard-to-find threading bug into your code.

Rationale: The more synchronized blocks there are, the more different permutations of execution orders there are for multiple threads. The more permuations you have to check, the more likely it is you (or the next programmer) will leave or inject a bug.

There are several ways to reduce the number of synchronized blocks in a piece of multi-threaded code. Here are three: (a) don't use threads3; (b) pack all the code that access the shared values into a single object, and synchronise on that; and (c) instead of scattering synchronize blocks throughout a method, declare the method synchronized.

Heuristic 3: Using Thread.stop(), Thread.suspend() or Thread.interrupt() is always the wrong thing to do.

Rationale: These methods halt a Thread's execution at arbitrary locations in the program, quite probably leaving the objects it was accessing in an inconsistent state. Elliotte Rusty Harold wrote about this.

Heuristic 4: Using Object.wait() or Object.notify() is almost always the wrong thing to do.

Rationale: For typical algorithms, the waiting effect of synchronize is exactly what is required. wait() and notify() do have legitimate uses, particularly in producer/consumer scenarios. However, every use that I have seen (outside of tutorials and UI code) has been mis-guided. 4

Heuristic 5: Don't optimise prematurely. First make it work, then make it fast.

Rationale: A golden-oldie of programming heuristics, this one is doubly pertinent to threading. The threading mechanims introduce myriad more ways for your program to go wrong, so avoid them if you can. If you need to use threads, use simple constructs such as coarse grained synchronisation. If that's not fast enough, then go back to the points where it is slow and fix those.


That's all. Use in conjunction with liberal doses of diligent design, careful coding and thorough testing.

1I am old enough to remember the early days of Java.

2This isn't supposed to be a dig at "the quality of Java programmers these days" or some such. There's plenty of good reasons why developers don't pay as much attention to threading as they used to.

3Far too much code uses multiple threads when it would be better off with just the one.

4Another heuristic: If a thread is waiting for another thread to finish using a resouce, plain old synchronize is what is needed. If a thread is waiting for another thread to produce something, then wait/notify may be needed.

By alang | # | Comments (0)
(Posted to Software Development)

Java vs. Python

9 AM May 2, 2003
Found this in a comment Simon Brunning made on one of his own posts :
Java is my wife, Python is my mistress. ;-)
Not quite how I would have said it, but eloquent, accurate and expressive of my programming language preferences.
By alang | # | Comments (2)
(Posted to Software Development)

Oh The Humanity!

10 PM May 1, 2003

This is one of the funniest things I've read for a while.

By alang | # | Comments (0)
(Posted to Stuff)

Kudos To Ian S

7 AM May 1, 2003
"Ian S" made this comment to Charles' post The Fishbowl: Swallowing Exceptions: Don't Do It!, and it deserves a replay right up the front of a blog somewhere.
I generally subclass RuntimeException for library code etc. There is one place where I swallow an exception:
int maxValues = Integer.MAX_VALUE;

try {
    maxValues = Integer.parseInt( 
            xmlElement.getAttribute("max") );
} catch( NumberFormatException nfe ) {
    //keep default.
}
Technically I should throw an IllegalArgumentException(nfe) or check for "", null, etc.

Anyway. This is what I paste in and commit to CVS whenever I catch (pun intended) a fellow coder swallowing exceptions. It rarely happens un-explicated now.

*ahem*

/* Will no-one*/ } catch( Exception e /* ! */ ) {
    //No getMessage() shall we ever see,
    //No System.exit( THIS_SHOULD_NOT_BE );
    //No RuntimeException( WONT_CATCH_ME );
    //No closure for Exception e,
    //for our programmer, with little thought,
    //has left Exception e uncaught!
}//Oh cruel bracket, how you limit the scope of his instance!
*bows*

Posted by: Ian S on April 30, 2003 11:00 PM

So, does 'S' in Ian S stand for Suess?
By alang | # | Comments (0)
(Posted to Software Development)
© 2003-2006 Alan Green