Don’t Be That Developer

Back in April of 2005, I came across a strange syntax in some java programming I was doing for work.

Class.forName("[S");

Back then, there was no convenient free StackOverflow site to quickly find an expert who would know off the top of their head what that syntax meant. And searching for “[” on Google certainly wasn’t a winning solution since square braces weren’t even indexed characters. How do you search for something that you don’t know the name of?

It took a while to find the answer. It turns out, it was a tricky way, using reflection of saying the same thing as short[].class

Really? Who would have guessed? It certainly wasn’t clearly documented anywhere, especially not in the code where it was used. And where it was used, there was absolutely no reason it needed to be using reflection and using some sneaky syntax.

Had the developer just kept it simple and written so much as a comment, or used a more straightforward, well-documented syntax the code would have been easier to maintain. We’re not playing Code Golf here (though even if we were, the non-reflection version still comes out shorter)!

JList that can be selected by keyboard entry

The default behavior of a JList is that when you use the keyboard to press the first character of a list item, the selection will jump to the first item starting with that letter. Additional presses of the same letter will cycle through all the items starting with the same letter.

For a small list, this functionality works great. For a larger list with hundreds of items however, you may not want to press a single key thirty times to get to the item you are looking for.

So I did a little research about how to make the list work more like windows, where if you type quickly, it will navigate to the item in the list that starts with the prefix selected. So you could type the first few characters of the item to jump much closer to or exactly on the item you are trying to reach.

It turns out this is not difficult but it requires a bit of boilerplate code. My example code here is a modified version of some example code released under the GNU license.

One of the keys to making this work is you need to define how long between key-presses should the system interpret the new keypress as a starting a new search vs. adding additional characters to the original search. CHAR_DELTA in this example code defines how long the system will wait between keypresses before presuming you’re starting a new search, here we are saying you have to type at least one key per second (1000ms) to add additional letters to your search. m_key is needed to track what key sequence has been typed so far, and m_time tracks the time of the last key-press in order to identify whether the threshold of time has elapsed to make this a new search.

     //elsewhere: jList1 = new javax.swing.JList();

    private static int CHAR_DELTA = 1000; 
    private String m_key; 
    private long m_time;

    private void keyPressHandler(java.awt.event.KeyEvent evt) {
        char ch = evt.getKeyChar();

        //ignore searches for non alpha-numeric characters
        if (!Character.isLetterOrDigit(ch)) {
            return;
        }

        // reset string if too much time has elapsed
        if (m_time+CHAR_DELTA < System.currentTimeMillis()) {
            m_key = "";
        }

        m_time = System.currentTimeMillis();
        m_key += Character.toLowerCase(ch);

        // Iterate through items in the list until a matching prefix is found.
        // This technique is fine for small lists, however, doing a linear
        // search over a very large list with additional string manipulation
        // (eg: toLowerCase) within the tight loop would be quite slow.
        // In that case, pre-processing the case-conversions, and storing the
        // strings in a more search-efficient data structure such as a Trie
        // or a Ternary Search Tree would lead to much faster find.
        for (int i=0; i < jList1.getModel().getSize(); i++) {
            String str = ((String)jList1.getModel().getElementAt(i)).toLowerCase();
            if (str.startsWith(m_key)) {
                jList1.setSelectedIndex(i);     //change selected item in list
                jList1.ensureIndexIsVisible(i); //change listbox scroll-position
                break;
            }

        }
    }

Java’s GregorianCalendar

Who would have thought up a calendar where the month starts at 0-11 but the days of the month run 1-31 (or so)? Its nice having full featured calendar utilities…but they could be slightly more intuitive to use, or at least consistent.

Dumb Java Generics Error Message of the Day

Type mismatch: cannot convert from List<SignPage> to List<SignPage>

And why not might I ask?

Today I implmented SHA-1 in Java

SHA-1 is a secure hash algorithm (called by some the successor to MD5), to be used as some sort of password generator for an application that I understand about as little about as I do the mechanics of how the SHA-1 algorithm works. It does a lot of crazy math and bitwise math to come up with this fixed length magic number.

But I guess none of that’s really important. What it comes down to is that I was given a website with some javascript source code, and they (work) wanted that in Java with some trivial changes to the input/output types.

Converting JavaScript to Java is Ugly with a capital U. Mostly because the more I work with JavaScript the more I’m fully convinced weakly typed languages are inane and obnoxious…especially if you should ever have the misfortune of debugging anything gone awry in such a language. But even though its ugly, it’s kind of fun, I like making things less ugly.

Dates in Java

how to get a non-deprecated time in java:

Date dateFromMessage = new Date(msg.getTimeAsMillis());
String expectedDateString = “1/19/05 2:50 PM”;

DateFormat d1 = DateFormat.getInstance();
d1.setTimeZone(TimeZone.getTimeZone(“America/Los_Angeles”));

String dateFromMessageAsString = d1.format(dateFromMessage);

dtm.publishSubtestResult(
dateFromMessageAsString.equals(expectedDateString),
dateFromMessageAsString + ” == ” + expectedDateString
);

Commenting Out Code

I think I scared myself, when in normal conversation(and by normal, I mean normal for a software engineer), I used the word OBERON. Yep, that’s right [the bane of my existence back in compilers class in college]. And not only did I say it, I was complaining that Java is not more like Oberon.

“If only Java allowed nested comments like oberon…”

Because, as it seems, Java does not appear to have any embedded language features that let you quickly and non-destructively comment out a large block of code which includes /* c style comments */, function headers, and does not necessarily compile where you are teleporting it to. If it were C, I could just add a #if(0) around it. Two short lines, and the entire function is commented out, non-destructively.

The only way I’ve successfully commented out entire functions is the macro and/or search and replace beginning of line technique to slash-slashify every single line. But that’s ugly ugly. ESPECIALLY when the file already contains //ified code, which is NOT my doing…and you can’t tell them apart. So then you start having to do something really ugly like //JRW// as the prefix for each line. Couldn’t I just if-zero it all out of my hair? I don’t want to be spending my time right now figuring out what includes I need, and what to do with these paramaters, and local variables I don’t have here…

or if only you could do nested c-style comments like oberon. (* cuz comments like this (* could be nested and *) that made everything happy, cuz you could comment out code with comments in it…and easily and cleanly… *)