Yeah, that's public, Java.

Having to program in Java is a real eye-opener. It’s really not something I enjoy, mainly because I know there are better ways to do just about everything other than “the Java way”.

Take visibility, for instance. You can declare attributes and methods as private, protected or public. But if you have two objects of a particular class, they can access each others private variables. How fucking crazy is that? I mean, something is hardly private is a different object can still access it!

Another place where visibility is fucked up is in terms of methods and availability of these. If I have a class that is not defined as a public class, and I have an instance of this class, I can find out what it’s declared methods are. But I cannot invoke them, even if they are public!

I’ve got a project where I have to build a parser, and evaluate expressions. Sometimes there is a statement that can affect the state of the afore-mentioned object (which is in turn a sub-class of JFrame).

One of the statements is to resize the JFrame, which I can do by using the .setSize() method on this object. However, I cannot declare my own methods, even as public ones, and then call then from the client class.

Seriously, this is shit. All I want to do is basically pass a message to this object, and there’s no way for me to do so without changing the visibility of the class. I have a reference to the fucking object, I just can’t really do much with it.

Prolog v Java

One program I tend to get around to writing in any new language I learn is a Sudoku solver. I originally wrote one in python, that solved every puzzle I could throw at it (although it had to guess and backtrack on failure in some cases).

Recently, I wrote one in Java. It was three classes plus a Driver/Main class. It took hours to write (at least the whole length of Phar Lap), and eventually it worked. I spent quite a while fixing up all of the syntactic errors I make in Java after programming in better languages again.

I then wrote one in Prolog. It was amazingly simple - it just defines a sudoku puzzle as a list of lists (each of which is 9 elements long), states that each element in each of the lists must be unique, and that each element in the first position of each list (columns) must be unique. Next, it states that each 3x3 grid must be unique, and that each element must be an integer of range 1-9.

That’s it. Solved.

My unique/1 predicate takes a list of items, and succeeds only if each item in the list is unique. This is simple:

  1. An empty list is unique.
  2. A list of one item is unique.
  3. A list of the form [A,B|X] is unique if A and B are different, and [A|X] and [B|X] are also unique-lists.

I also use a predicate that indicates a variable should be of the value 1-9, it’s possible to use advanced techniques and something called “Domains”, but I couldn’t get this figured out.

The only trick then is in the definitions. The simplest to understand, but messiest is to define the elements in the sudoku puzzle as each having unique names ([[A1,A2,...,A9],[B1,...]] and so on), and then passing some lists to unique, ie all ‘Ax’ elements, all ‘X1’ elements, and so on.

The coolest thing about Prolog is that you don’t need to say how things will happen, but just what the desired outcomes are. This can be dangerous - it’s rather easy to write something that will be executed in a ridiculous amount of time, so you often need to think about how to narrow the search space as quickly as possible. In Java, I needed to have methods that would remove elements from a possibles list, and then check to see if there was only one element, in which case it’s the actual value that belongs there, and so on. This is all error-prone code, wheras Prolog’s backtracking does all of this for you.

The biggest benefit is that in a puzzle that is fiendishly hard, Prolog will still come up with a solution, wheras some other languages, using the algorithm I defined above may not. And, in Prolog, you will automatically get multiple solutions to a problem if they exist.

Can you tell I love Prolog?

Core Data vs. SQL Alchemy vs. J2EE

Three languages. Three different Object Relational Mapping systems. One operating system.

Over the past couple of days, I’ve been madly learning how to create programs in Core Data, using Objective C and Cocoa. It’s given me plenty of food for thought, and made me perhaps think that it’s not that SQL Alchemy rocks my world, it’s just that J2EE/EJB is just ORM done wrong.

I actually got exposure to SQL Alchemy in detail before J2EE - I first came across them at the same time, but using SQL Alchemy was at work, and I basically had to learn in 2 days what a full semester worth of J2EE taught me. Perhaps that was just because learning the python stuff was so damn easy.

Now that I understand just how cool an Object Relational Mapping is, getting into Core Data was easy. Creating the same schema in SQL Alchemy (actually, using Elixir, so it was just object creation), and then in a Core Data xcdatamodel - basically the same process, was even simpler in Core Data: simply because it is a GUI tool, and you can see the whole model in one go, instead of having to scroll through a text file examining classes.

But doing GUI programming using the ORM is where Core Data really shines. Using Cocoa Bindings, you can just plonk down an NSTableView, and tell the object where it gets it’s data from. If you have two GUI widgets using the same data model, and you change selection in one, it even changes the selection in the other!

Core Data also helps look after Undo, Saving and all other sorts of goodness I haven’t even come across yet.

The only thing that Core Data isn’t good for is a multi-user system - or more precisely, a system where multiple users are accessing the data at the same time. I’ve used SOAP as the messenger format, where I had a rich client accessing services provided by my server, but this is cumbersome. I’ll just use Pylons, or perhaps Django to do a web application - where the interface is largely a Web Browser. In this instance, it will probably be best to just stick to a python-based approach. I’m tempted by WebObjects, but that would still require me to use Java.

If only Apple would release a distributed Core Data. I might be able to do something kind of cool with Distributed Objects, for a rich client, at least, but for Web, I may as well do the whole thing in python.

(One reason) why J2EE sucks dog balls.

I really don’t respect or like Java as a language. I’m not going to go into reasons why here, but I am going to bitch about J2EE and Enterprise Java app development under NetBeans.

Now, I’m not just a clueless student annoyed with stuff that doesn’t work because I’m a gumby. I write enterprise applications in python, apache and SQL Alchemy for my day job. It shouldn’t be as hard as it is to develop in NetBeans.

For starters, if I deploy my code and it fails, I shouldn’t be able to redeploy it again and it works. Same goes for building. I have found instances where I can build and it fails, and then an immediate re-build succeeds. And I’m not talking “Clean Build”, just a regular ordinary build.

More to the point, if I do an “Undeploy and Deploy”, and I get a whole load of exceptions, I kind of expect that the deployment has failed. But if I then do a build, it works.

And, it appears that if I build without a fresh redeployment, it fails.

This is just build and deployment issues. I’ve also had instances where code has failed, when I was pretty fucking sure it should have worked. I was throwing exceptions all over the joint (or, more correctly, the JVM or some other bit of technology was), and they were meaningless. A redeployment and the associated re-build, and it worked.

Developing a similar application in python+SQL Alchemy is faster, doesn’t appear to run much slower, and is much, much easier to read later. Yet, it is not taken seriously, because it isn’t Java.

Ugh.

Java 6 Breaks JComboBox Events

It took some figuring out, but I came across what appears to be a deliberate bug in Java 6 SE.

Under Java 1.5, you can rely on a JComboBox to generate ActionEvent actions whenever an item is selected from the list - even if that item is already selected.

Java 6 SE does not do this. You only receive an ActionEvent when you select a different item from the list than is currently selected.

For most cases, this will be fine. If selecting something should update other objects or properties, then this might not be the case.

There are a couple of workarounds. The one I chose uses .setSelectedItem(null) when another event is generated that would need to be ‘overridden’ by the JComboBox choice. Another is to create a subclass of JComboBox that performs the desired behaviour. But this is too hard.

It comes about from using ComboBoxes where they aren’t really designed. The shouldn’t really be used for actions to begin with, but in some cases they are.

This is yet another example of Java breaking previous code.

Procedural Programming

A big thing is made about teaching Java, and using Object Oriented techniques. “You can only program using Object Oriented methodologies in Java.”

Crap.

You can, and I have noticed it happening more, easily fudge up a procedural programming paradigm in Java.

Static methods appear as procedures and functions.

In CP2A, this is exactly what is starting to happen. Instead of building on the OO crap, stuff is being done in public static void main(String[] args), which is all procedural.

This is fine, but why bother teaching OO under Java first, and then this after? Just skip the middle man and start with the procedural stuff. I’d rather have done Pascal again… nah, just kidding.

Chess, just for fun.

We had a homework exercise the other day, that went something like this:

Consider the design a class, ChessBoard, to represent a chess board (an 8 by 8 grid of squares) where each square can have a single chess piece on it (pawn, rook, knight, bishop, king or queen) which is either black or white. Discuss the design of move methods for each type of piece. The methods should have parameters which specify where the piece currently is and where it is being moved to. Each method should check if the move is valid (the correct type of piece is on the square, the move is to a square that is on the board and it does not contain a piece of the same colour) - a proper implementation would also check that none of the other rules of chess are being violated.

Give declarations and initializations for each of the instance variables the class (ChessBoard) would need and declare any other classes necessary. Add a method to ChessBoard that will place all the pawns of a particular colour on the board. White pawns occupy the entire second row (1 pawn on each square of the second row) of the board while black pawns occupy the seventh row of the board.

Complete the implementation of the moveKnight method below and the class Position (you could just use java.awt.Point). Knights move 2 square either horizontally or vertically (along rows or columns) and then 1 square to the left or right.

boolean moveKnight(Position currentPosition, Position newPosition) { ...

Now, that was just not enough for me. So I designed and implemented, just for fun, a framework to handle all of the pieces, and all of their possible moves. I went a bit full-on: my classes are listed below.

  • ChessGame
  • ChessBoard
  • Location (each square is a Location, this makes it easy to do stuff later on)
  • Team
  • Move
  • Piece (abstract)
  • King, Queen, Bishop, Knight, Rook, Pawn

Now, most of this is fairly easy: using OO is golden for something like this, where there are stacks of cases where inheritance means you can implement it once, and this is fine for most cases, but where not you can just override it once or twice. And having this level of abstraction in each case has also been quite handy. For instance, by having a Move class, which has a Piece, and two Locations (start and finish), it’s a simple thing for me to keep a record of the game (LinkedList of Moves), and calculate things, like whether a particular piece was the last to move (for en passant).

There are actually only a couple of tricky things to worry about with Chess. Most of these are related only to the King: you have to check before each move to see that the move won’t put your team’s king into check, and if you are already in check, then ensure that the move you make takes you out of check. Otherwise, it’s a fairly simple algorithm. To set up the rules, not to actually play.

As it turns out, the Pawn is actually the hardest piece to code for, since it moves in a variety of different ways in different contexts. It’s harder to code for the normal behaviour (ignoring en passant) than it is to handle castling.

The only thing I haven’t implemented yet (apart from being able to drag and drop or click on pieces) is whether the game is in checkmate. I’m not quite sure how to do this, just yet.

Anyway, here is a screenshot of my simple chess game. It’s the biggest thing I’ve written in Java so far, and doing all of the UI code, was, as expected, a whole lot more painful than Cocoa.

Picture 1.png

I still don’t have my head around the Drag and Drop stuff to do with Java, nor really at this stage have I figured out how to make each Location clickable, and then use this to execute moves. I think I’ll make it so that a click checks to see if a piece is of the right team, and present in the chosen location, and then highlights that square so you can see what piece you are moving. Then clicking on a second Location will move that piece to there, if it is a valid move.

I guess after that, I just need to make the intelligence to play…just kidding. That might wait till I am studying AI, next semester…

Revision Control as timing guide

I use Mercurial for all of my new work. It’s a great distributed revision control system. I even use it for all of my Uni programming, and other work. It allows me to easy switch back to previous checkpoints if I need to get them marked off, for instance.

The work we have been doing in one of my topics is still way to easy, although it is getting a bit better. But using Mercurial allows me to see how long each of the tasks took me to do.

Not sure how long the first Checkpoint took, as I didn’t have a commit to do then. But the next one took exactly 15 mins. The third one took 14 minutes, and the final one took 24 minutes. That last one was a fair bit of refactoring though, so that wasn’t too bad.

As for the bonus checkpoint? That can wait until morning.

Java and Arrays

Java almost handles arrays well.

Almost.

Maybe I’m spoilt by python, but having datatypes that are effectively a hybrid between lists and arrays is excellent. You get both of the advantages - being able to iterate easily, and access by index (attributes of arrays), and having dynamic sizes and non-sparse lists (the only decent attributes of lists).

In fact, the text I am reading now has a three-and-a-half page code fragment called “Partially-filled lists”, which is about 200 lines of code, which implements what I describe. Except the upper limit of the size, which must be determined at compile-time. And it requires a new class if you want it to be for anything other than doubles, or whatever you have written it for.

The other thing which was bugging me was the looping of arrays. In python you can do cool stuff easily iterate over elements of an array. Recent versions of Java can also do this.

Python:

1     for element in theList:  
2         print element

Java:

1     for (element: theList)  
2         System.out.println(element);

It gets pretty close. I think I still like the simplicity of the python notation - brackets only where they are really required to indicate function/method calls, and for expression ordering. Having a required bracket around if test-expressions and the like just makes me think if, switch and so on are functions. Which they can’t possibly be, since Java doesn’t have functions, only objects and methods.

And don’t get me started on braces…

Back to Uni

After a nearly 10-year hiatus, I’m back at Uni. And loving it.

I’m currently sitting in the Flinders Uni “Coopers” bar, having a nice cold Pale Ale. My first day of Uni was today, and so far it’s pretty cruisy.

I actually finished the first two afternoons’ work in the first half of the first afternoon. The lectures didn’t really give me much new, it’s all just aligning what I already know about OOP with the syntax of java.

The thing that actually took me the longest today was remembering how many degrees are in the internal angles of a regular pentagon. I ended up having to fire up a python interpreter to keep a track of all of my maths. I think I would have finished in half the time it took me otherwise. That, and having to remember to declare variables…

So, Java is looking easy so far, and from what I can see the next 2.5 weeks are going to be more of the same. About time I started to get High Distinctions, I think. I’m finding plenty of time to listen to Late Night Cocoa, and learn Objective C/Cocoa while I learn Java.