Archive for Java

Code Spelunking

Alex Miller writes about code spelunking techniques for when you’re digesting someone else’s code. He offers some good advice, particularly for tracking down call hierarchies and implementors (and some useful Eclipse shortcuts). What was missing, I thought, was the easiest one of all:

Draw a picture.

He did show a project dependency graph, but I find it’s really best to draw a simple picture, not even in UML, just in whatever comes naturally to you. On this picture, keep the real names of the classes, but then give them useful names, or small summaries, and describe their general responsibilities.

Use this diagram as your map, and don’t complete it for perfectionism, but only follow interesting paths. Invariably you’ll end up pruning paths as it’s clear that it leads to property holders, or utility functions (which is part of classifying the objects, as Alex writes) in which you’re not interested. But in particular, when you draw your own diagram, you have a bread crumb trail to look back on, so when the names don’t make sense, or you can’t remember the big picture, you’ve got your notes of what you’ve already seen.

Besides, if you’re drawing a picture, then the next developer who comes along will need to draw a picture too. So you might be able to do a formal diagram and put it into the project, helping others pick up on the architecture that much faster.

Comments

Java 3D vs. Java OpenGL

I have been experimenting with Java3D and JOGL as 3D libraries. Both are mature, and perfectly acceptable for anything I would be doing with them.

Java OpenGL uses JNI (meaning the underlying system must support OpenGL), and it doesn’t use Java3D’s scene graph approach. With Java 6, Java2D and JOGL can work closer, resulting in swoopy features like a Swing button with a 3D icon image.

Java3D was meant to be a Java wrapper for DirectX and OpenGL. It, too, uses JNI, and it seems there is no sophisticated 3D graphics library that doesn’t. But, as Alexander Schunk writes, JOGL makes Java3D somewhat ineffective as a unifying library among the 3D graphics technologies.

So, I don’t know which I will go with. There are some fantastic books on OpenGL, and it’s certainly a useful skill set. It’s too bad you can’t easily port things over from OpenGL to the scene graph API of Java3D. They’re such different approaches, but that’s why they’re two distinct projects.

Comments

Database Programming Simplified

Ah hah! The solution to my database woes was the PreparedStatement.

The only serious database-intensive application I’ve written used PHP’s Pear DB package. And PHP was just a lot nicer about typing and variable substitution, so I found myself doing less of the quote-escaping and type checking necessary in Java. So it is with great relief that I discovered prepared statements.

It works just like a regular statement, in that you create it off the connection:
PreparedStatement prepstmt = conn.prepareStatement("SELECT * FROM ITEMS WHERE NAME=?");
But, as you can see, the SQL string substitutes values with question marks. The fantastic thing about it is that this statement is not typed. By this I mean that you can put an integer or a string into the statement without changing the SQL. This cleans up a lot of the messiness of the SQL requirement of having single quotes surround strings. And because Java String concatenation is ugliest for short strings, it cleans up your SQL statements several fold, in my opinion.

To set it, all you have to do it:

prepstmt.setString(1, "myname");
ResultSet rs = prepstmt.executeQuery();

So here’s a before:

int rows = stmt.executeUpdate(”INSERT INTO “+
“ConfigData (configkey, configname, “+
“configdate) VALUES (”+configKey+
“, ‘”+configname+”‘, “+configdate+”)”);

And the after:

String sql = "INSERT INTO ConfigData(configkey, configname, configdate) VALUES(?, ?, ?)";
... //Create the prepared statement object
prepStmt.setInt(1, configkey);
prepStmt.setName(2, configname);
prepStmt.setDate(3, configdate);

Even without the performance gains of re-using these PreparedStatements, the cleaner String notation is a great solution for queries with several variables.

Comments

Database Programming the Hard Way

I imagine a lot of people have this problem – There’s a little persistent data for an application, it would be easiest to be in a database, but the frameworks are overkill. The solution, or so I’ve heard, is to use POJOs – Plain Old Java Objects. But, if I understand this correctly, I’m still left to hand-code the translation from field variables to database variables, usually in a rather tenuous way (i.e. changes to the database required multiple changes to the object – the field name, the getter/setter name, and the string of SQL that inserts/updates it).

My Java objects that actually hold data tend to end up looking like this:


public class ConfigData {
private String configName;
    private Date configDate;
    private int configKey;

    //getters
    //...

    //setters
    //....

    /** Insert items into database */
    public void insertSelfInto(Connection conn) {
        Statement stmt = conn.createStatement();
        int rows = stmt.executeUpdate("INSERT INTO "+
            "ConfigData (configkey, configname, "+
            "configdate) VALUES ("+configKey+
              ", '"+configname+"', "+configdate+")");
        if (rows == 0) {
            //throw an exception
        }
    }

This is really ugly. I mean nasty ugly. I mess up the single quotes around strings all the time, I’m crafting SQL by hand based on variable names and column names that are hard coded, etc. It’s not obtuse, and it is straightforward, but it is definitely finicky.

So I’ve been trying to determine if this is really how POJOs are supposed to work, or am I missing some intermediate step? This is sort of the lowest level POJO you could use, but is there something short of a framework, or adding another JAR to my project that would give me some more stability, or at least readability? I have yet to discover it, if there is.

Comments

Ambient Orb

I bought my partner an ambient device a year or two ago. It’s basically a frosted glass orb with some LEDs on the inside and a wireless receiver. The LEDs change color and can pulse at different rates, based on the command received by wireless (same coverage as cell phones). As we were living apart at the time, I paid for the subscription (about $7/month) to be able to change the color of the orb over the internet (it’s called the developer’s channel). I wrote some PHP to map the colors to my mood or my work level, things like that.

The purpose of Ambient Devices’ products are to convey information in neither a pull method (i.e. polling your email for new mail) or a push method (i.e. your phone ringing). In reality, it does both, just at a very low priority. Some people set it to stocks or the weather, or traffic, and whenever they want that information, they can glance at it to see the current state of their chosen subject.

So, with my partner moving in with me next month, I got the hardware developer kit, which is essentially a circuit board that connects to the serial port on your computer, and the other end into a connector on the orb. This way, I can send my own signals, and not pay to use their server to send the wireless commands. They include a small Java GUI to show you how you can control it, and the Java API they’ve created allows you to specify the color and pulse, and then through native code, push that out to the orb.

It’s unclear whether the orb must stay connected to the PC to keep its current state, as it is set to receive wireless signals through Ambient’s servers. These would overwrite the most recent computer command if it were not connected to the computer still.

I’m looking forward to creating something to control it, probably a servlet, although I could use some practice with RMI.

Comments

And… we’re back

It’s been a while. 7 months, to be exact. I have since joined the workforce and am working as a Java developer at an ERP company of sorts, the same company for which I interned. I rejoined the tools team, and they put me right back on the server code.

Within a few weeks, I was drafted into a special interest team whose only goal was to improve “performance” and memory management on the server for high loads. I say “performance” because, like so many managers, the one term can be used in suitably hand-wavy fashion to encompass response time, memory usage, throughput and CPU usage, without actually committing to anything at all.

The most infuriating conversations of all go something like this:
Developer: We’re implementing feature Y because the current feature X uses too much memory.
Manager: Very well, how much will feature Y improve performance?
Developer: It will improve memory usage. I can’t speak to how it will affect throughput until we see it. But we won’t get the OutOfMemoryErrors.

[Next day's meeting]
Manager: So, our developers tell me we’re implementing feature X to improve performance. Can you tell us how much faster feature Y will be than feature X?
Developer: No.
Manager: But you said it would improve performance.

And so on. The issue at its root is that “performance” is a horrible, huge term. And nobody wants to say that we’re willing to sacrifice throughput to help memory usage, even though high memory usage has led to stability problems. So nobody will say “we need to have 100 transactions per second,” instead, they say “we want as many transactions per second as possible.” And around it goes…

So there it is, my life resembling Dilbert more and more every day. Aside from work, I’m looking into a master’s degree in computer science (which necessitates taking the GRE), and I’m still working on a Java certification. The last attempt was held up by an Operating Systems course that required learning C instead of studying on Java.

Until next time…

Comments