Apr 27 2011

How To Print The Alphabet in Java?

In Java, the primitive value of type char can be converted to the primitive int. An an integer within the range of a character can be converted to a char. For example, the ASCII character code for the character A is 65, for B is 66, etc. Because of a char value can be interchanged with the integer value that represents its character code I can create a loop that starts from the letter A and stops at the character Z and I increment one character at a time. Here is the code snippet to print each letter of the alphabet in a loop.

for(char c = 'A'; c <= 'Z'; c++) {
    System.out.print(c);
}

Apr 25 2011

Java String Conversion Puzzlers

In Java, object coercion from one type to another can led to interesting results, and possible bugs when done implicitly. For example, a common type conversion bug is when you have a method that accepts a primitive boolean but pass it an an object of type Boolean. If the object is null, the conversion from a Boolean object to a boolean primitive will cause a NullPointerException.

But mixing between Strings, characters, and integers can result in an interesting mix of results. For example, I think that any Java developer would have some doubt in describing the output from the following Java code.

System.out.println("Hello, "+(char)('A'+1));
System.out.println("Hello, "+('A'+1));
System.out.println("Hello, "+'A'+1);

The one rule to remember about coercion is that if you are performing a calculation with two different types, the least accurate type will be coerced or converted to the more accurate. In this case, adding a character and an integer will result in converting the character to the corresponding integer value before performing the addition operation. Because the integer equivalent of the char value ‘A’ is 65, then ‘A’+1 = 66. When adding between a string, character, and integer the character and integer are converted to strings because concatenating the values into a new string.

"Hello, "+(char)('A'+1); // Hello, B
"Hello, "+('A'+1); // Hello, 66
"Hello, "+'A'+1; // Hello, A1

Nov 16 2010

App Engine Learning Library

One of the most interesting technologies right now is Google App Engine. Google App Engine is a framework that runs Google’s cloud. Developer and programmers can program in Java or Python and upload their applications to be hosted in Google’s infrastructure. Google has a generous free plan, but if your application picks up traction you to buy additional bandwidth. Google App Engine has some decent documentation but I also like to follow in a book or two. Here is a short list of books on Google App Engine in hopes to get you started.


Mar 8 2010

Top Worst Java Errors

I’ve had my fair share of Java bugs. There is a stage in a programmer’s career that he or she either knows that they rather manage a convenience store or that they can debug common Java errors just by the way the code smells. Here are my list of worst common Java bugs I have been frustrated to solve. These issues have come up more than once, most often in code that I inherited, and had to fix under a time crunch or tight deadline.

mkdir
I’ve had to fix a few bugs related to the mkdir() method in the File class. The mkdir() method creates or makes a new directory. The mkdir() method only creates one directory. But in many situations, especially if the end user is supplying the path of the directory to be created, you will need to crate a whole new directory hierarchy. Often times you will create a directory and subdirectories at one time. In these situations, you want to use the mkdirs() method instead.

Index Of
Most software bugs are caused by assumptions made by the programmer. One common assumption I see developers making is that file names have only one period to separate the file name from the file extension. It is common to see code that finds the first period and everything after that period is assumed to be the extension. Other assumptions regarding file names include that extensions are three characters long or that the file name does not have special characters. The following code snippet is a dramatization of code I have seen in the field, which incorrectly tries parse the file extension.

String filename = "a.file.path.ext";
int index = filename.indexOf(".");
String extension = filename.substring(index);

A different approach, which would have the desired result is to use the lastIndexOf() instead.

Null Equals
I’ve seen a whole slew of null pointer exceptions due to this sort of Java bug where a possibly null object reference will be used to check the equality of a hard coded constant. Here is the code snippet of what I mean.

boolean equals = maybeNullObjectReference.equals("CONSTANT");

The object reference may be null, so you need to check for null values. I found that if you switch your thinking, you can write less code and still achieve a better solution that having to constantly check if the object is null. A safe approach is to use a object that you know is not null, the constant value.

boolean equals = "CONSTANT".equals(maybeNullObjectReference);

Equals
Yet another Java bug that can be easy to miss is the use of the Java equals operator instead of the equals() method. The equals operator returns true if the two object references you are testing point to the same object instance. The equals operator compares the equality of the object references, not the object values but since it reads the same it is easy to overlook.

Map Key
The worst Java bug that I had to ever deal with involved the use of mutable objects as keys in hash maps. The implementation of the Java HashMap is really simple, the hash code of the key is used to locate the bucket in which to store the map entry, which consists of the key/value pair. Once you put a key/value pair in a hash map you should not change the value of the key, ever, in any way that changes the hash code. If the key is changed where it generates a new hash code, you will not be able to locate the correct bucket in the HashMap that contains the key/value pair. I had a scenario where key/value pairs were stored in a HashMap, then the keys where updated generating a new hash code, and there after the value was not able to located.


Jul 22 2009

Don’t Turn a Code Review Into a Code Rant

In programming circles and when talking about code, I’ve often hear mentioned the Perl slogan “There’s more than one way to do it.” Thinking about the many ways we do it, whatever feature ‘it’ represents, I believe that the root cause of many of the software bugs we encounter are because engineers implement the feature in more than one way, then refactor it down the line, then add new conditions, then forgot how it did what it did. This often occurs because programming is like fashion, each season brings about a set of new best practices and technologies. We update the implementation to adapt to the current best practices, new technologies, and new features and don’t remove old bit rotten code.

Recently I a debate with a fellow engineer whose code I reviewed. As it is often the case, we had some existing functionality which we wanted to update with a feature. Most of the code review revolved around one existing method whose existing code looked something like the following.

public void setValue(DataRow dr) throws DataException {
  dataHelper.setValue(dr, false, true);
}

For the sake of this example, imagine that DataRow is a map of data that represents a row of data from a database and contains the meta-data of the columns it contains. The new functionality need to support a DataRow with a less number of meta-data, columns, than normally expected. We called this new feature partial value and so it was initially implemented as follows.

public void setValue(DataRow dr) throws DataException {
  dataHelper.setValue(dr, false, true);
}

public void setPartialValue(DataRow dr) throws DataException {
  setPartial(true);
  setValue(qube);
  setPartial(false);
}

Believe it or not, I had a very difficult and long drawnout debate with the engineer that implemented the above code. In my mind, there is no debate, the above code can be made to improve. In the engineer’s mind, this was good enough for this feature for the time allotted for the the current specifications for this release and for whatever other reason he counjured up.

One of the concerns I originally brought up with the initial implementation of setPartialValue was that if the setValue method throws an exception after having set the partial state to true, then the code will break out of both methods leaving an improper partial state behind. This will cause problems because the partial boolean field will have an invalid state which will caused problems if you the setValue method is called at a later point. Another problem, with this sort of style of programming, is the following scenario. Imagine that instead of a simple primitive boolean the partial property required an object reference that retained a lot of memory and you had the same exception, the memory for that field might not be garbage collected.

The sort of bugs that can be caused by the above implementation lead me to the following rule of thumb: Avoid instance fields. Always question the need for instance property. Try to be a team player and pass the object reference as a parameter down the stack. If you only need this little bit of state information for a method call, pass it as a parameter!

I couldn’t believe we had this much disagreement over three lines. At that moment I felt that code reviews are another form of micromanagement, but then I remembered who is the one that gets called if there is a bug in the system…. Yeah, me! The approach I was advocating did not require a object instance to keep the state of a boolean, which was only used within the context of the setPartialValue method call. In my approach the set/getPartial methods are not needed and it could have been refactored to the following.

public void setValue(DataRow dr) {
  setValue(dr, false);
}

private void setValue(DataRow dr, boolean partial) {
  dataHelper.setValue(dr, false, true, partial);
}

public void setPartialValue(DataRow dr) {
  setValue(dr, true);
}

The engineer countered that it “does not look nice” aesthetically to have a method call with to many parameters, and that we can’t just add parameters to methods whenever we need to pass another value. Touché. To this I responded that four parameters is not a big deal. Even though four parameter will not negatively affect a method signature, lets imagine that a method signature grew to 10 parameters, this can be solved by encapsulating all these parameters to one object. Programming languages such as Ruby use map literal for optional parameters and long parameter method signatures.

In the end, I won the debate but it didn’t feel like a victory. I doubted myself for pushing so strongly for what I know is right, in the end he was doing all the heavy lifting and this was just one small aspect of the feature as a whole. There is a line that if crossed you will be considered a micromanaging standard fascist, but that if you do not enforce you will inherit unmaintainable code. Coding standards goes beyond naming convention and third party libraries. There is a fine line, and you need to walk the line.


Jun 16 2009

Top Griffon Tutorials and Resources

Griffon is the rapid desktop development equivalent to Grails or Ruby on Rails. Griffon is a desktop application framework written in Groovy, a scripting language that runs on the Java Virtual Machine. Just like Grails or Rails, Griffon is very DRY and opinionated, comes with generators, and separates your models from your controllers from your views.

Griffon is a new project with the most recent release clocking in at version 0.1.1. Even though Griffon is new, it is based mainstay libraries such as Groovy, Swing Builders, and SwingX. Even with a version number of 0.1.1, Griffon provides enough features to develop functional and complex UIs. To help getting started with Griffon, here is a collection of Griffon tutorials and resources that I have found insightful and helpful.