Monday, March 29, 2010

Substring on a huge string

The garbage collector won't be able to clean up the underlying byte array.
public static String getIntro()
{
    String novel = novelFactory.writeNovel();
    return novel.substring(0, 140);
}

Monday, March 22, 2010

StringBuffers that exist within a method

This won't be the biggest performance hit of all time, but no one seems to use a Vector when an ArrayList is sufficient. StringBuffer was released before StringBuilder, and old habits die hard.
public static String concat(Iterable iterable)
{
    StringBuffer buffer = new StringBuffer();
    for (String string : iterable)
    {
        buffer.append(string);
    }
    return buffer.toString();
}

Monday, March 15, 2010

Depending on concrete classes

This should at least depend on List, but would be even better to depend on Iterable.
public static String concat(ArrayList list)
{
    StringBuilder builder = new StringBuilder();
    for (String string : list)
    {
        builder.append(string);
    }
    return builder.toString();
}

Monday, March 8, 2010

I just can't handle it

There are better ways to handle exceptions...
public static InputStream readFile(File file)
{
    try
    {
        return new FileInputStream(file);
    }
    catch(Exception e)
    {
        System.exit(1);
    }
}

Sunday, March 7, 2010

Bad optimization

You can prevent third-party libraries from doing this by including the "-XX:-DisableExplicitGC" option at the command line (see http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp for details).
public static void resetList()
{
    this.list = new ArrayList()
    System.gc(); // unnecessary at best!
}

Is there any point to checked exceptions?

Interesting discussion here: http://googletesting.blogspot.com/2009/09/checked-exceptions-i-love-you-but-you.html
public static void doThing(Object thing) throws Exception
{
    // no op for now
}

This is actually possible

public static void goodbyeWorld()
{
    System.out.close();
    System.out.println("Can you hear me now?");
}