Is Java growing in the right direction?

Over at Vanilla #Java, there was an article showing Java’s popularity as a language compared to others and then it ranked them based on the level of abstraction at which they were designed.  The most popular language is C with 17.9% and next was Java with 17.4%, followed by Objective-C, C++, and C#.  So, of the top five languages, four are C or direct decedents of C and they all lower-level languages whereas Java is a higher level language.  He argues that although Java is adding lots of neat higher level features like Lambda expressions, Type Annotations, and Virtual Extensions they’re neglecting the ideas of structures and other lower levels of constructs that are important in areas like mobile and embedded systems which are likely to become more dominant in the future.

From my perspective, I think adding in more higher level constructs is a great thing as the cost of computation and storage is becoming negligible at this point for all devices.  It’s much more important to focus on making the programmers more productive since they’re the true overhead cost of product development at this point.  Now, I don’t mind Java supporting lower-level ideas like structs (I still enjoy writing C/C++ code) but I wonder about the time it takes to implement a lower level feature when hardware has Moore’s Law working for it.  Right now, I think Java (and C# for that matter) makes good trade-offs between high-level and low-level features to keep itself relavant in today’s market even if it is missing out on some of the embedded device market.

I’m completely ignoring the state of the alternative JVM languages like Groovy, Clojure, Scala, etc. which I think add some very nice possibilities to the JVM programmer.

If anybody is reading this and cares to comment on the state of Java, feel free to do so in the comments below. 🙂

Java and Immutability: Creating a Simple Builder

The more I look back on what I learned about programming in school (junior high, high school, college, etc.) I realize that although it made a great base on which to learn, it really does not get you ready for problems you’re going to see in the real world.  Of course, even then the problems are always changing and what you thought was the best approach a year ago, a month ago, or even within the last hour, isn’t.

One of the largest hurdles to jump over (besides recursiveness), in my opinion, is mutable versus immutable.  The main reason is because you’re taught from the time you start programming through college (ignoring those of you who took a Haskell class) you’re only taught using C, C++, or Java.  All languages that are mutable state programming languages (yes, you can apply immutability to them and I’m getting to that) and although (perhaps) easier to learn can lead to some hard problems down the line when you have to start thinking about scalability and parallelism.  Josh Bloch, of Effective Java fame, has said that unless you have a really good reason to make a mutable class, you shouldn’t.  And if you have to make a mutable class, limit the scope of it’s mutability.

Now, as the title of the post implies, I’m going to talk about how to make immutable objects in Java and touch on some of the issues that you might run into along with how to make a builder class to instantiate this new immutable object.  There are a few conventions that you apply to an object that will normally make it immutable with a few small exceptions.

  • make the class final
  • make all fields final and private
  • if a field is mutable make a defensive copy on a get
  • only set the fields in the constructor
  • do not allow setter methods

Now, these steps will get you there but, there are a few gotchas that people normally don’t think about.  For instance, most classes with the Iterable interface or an interface that allows removal from a set or list even if it is defined as final in the class if you pass it out to the caller using this pattern:

public Iterable<SomeType> getSomething() {
  return this.myIterableSomething;
}

are in for a big surprise (unless you’re using an immutable list) because the caller can then use the remove() method on that Iterable list that you returned.

Now that you’ve got this wonderful (and hopefully) immutable class, another awesome thing you can do is make a builder class to help construct the object.  This is especially helpful if your class takes a large number of inputs into the constructor.  There are many ways to make builder classes but I’m going to demonstrate my favorite one: a static class inside of the class you want to create.

Creating the builder is really very simple.  First, have a class you want to make a builder for, in this case, let’s use SimpleClass.

final public class SimpleClass {
  private final int a;
  private final int b;

  public SimpleClass(int a, int b) {
    this.a = a;
    this.b = b;
  }

  public int getA() { return this.a; }
  public int getB() { return this.b; }
}

Now, lets create the builder class inside of the SimpleClass, like this:

final public class SimpleClass {
  .. snip ..

  public static class Builder {
    private int a;
    private int b;

    public Builder() {
      //assign some default values...
      this.a = 0;
      this.b = 0;
    }

    public Builder setA(int a) { 
      this.a = a;
      return this;
    }

    public Builder setB(int b) {
      this.b = b;
      return this;
    }

    public SimpleClass build() { return new SimpleClass(this.a, this.b); }
  }
}

With this, we now have a very barebones builder class for SimpleClass.  In practice you’d take values that absolutely have to be set in the builder’s constructor and set reasonable defaults for the optional values.  You’d then use the set* methods to set the optional values for the class.  Additionally, if you only want the user to construct objects through the builder class you can set the constructor on the class to private, leaving you with a SimpleClass listing:

final public class SimpleClass {
  private final int a;
  private final int b;

  private SimpleClass(int a, int b) {
    this.a = a;
    this.b = b;
  }

  public int getA() { return this.a; }
  public int getB() { return this.b; }

  public static class Builder {
    private int a;
    private int b;

    public Builder() {
      //assign some default values...
      this.a = 0;
      this.b = 0;
    }

    public Builder setA(int a) { 
      this.a = a;
      return this;
    }

    public Builder setB(int b) {
      this.b = b;
      return this;
    }

    public SimpleClass build() { return new SimpleClass(this.a, this.b); }
  }
}

To actually instantiate this class in practice you’d make a call like this in your code:

  SimpleClass mySimpleClass = new SimpleClass.Builder().setA(10).setB(11).build();

And, whala! You’ve created an immutable class using a builder!

With this, you’ve taken the first step toward better coding in the real world and on problems that have you dealing with scale and parallelism.  I’ll hopefully write about scale and parallelism in later posts, so stay tuned, and if you have anything you think I should write about or a place where I’ve screwed up, let me know in the comments below! 🙂

If you’d like this source code in a nice form, check it out on GitHub.

JewelCLI: a simple CLI interface for Java

I’ve been working on a command-line interface for my PhD work and was initially doing the parsing of arguments by hand which was becoming extremely unwieldy so I decided it was time to jump into the OpenSource waters and see what was available.  I took a look at many CLI libraries (you can see a whole list of them here from JOpt) but settled on JewelCLI due to it’s simple, powerful interace and ease of use.  It might not be as powerful as Apache’s Commons CLI or CLI2 but it fit my needs perfectly.

Not to steal any thunder from it’s website, but as a quick example, all you have to do to use it (other than managing the dependency through Maven or whatever your tool of choice maybe) is three steps.

First, create an interface class.

public interface MyInterface {
  public String getFilename();
}

Second, annotate that interface class with the JewelCLI annotations.

public interface MyInterface {
  @Option
  public String getFilename();
}

Third, use JewelCLI’s factory methods to parse the command line arguments.

...
try {
  MyInterface myInterface = CliFactory.parseArguments(MyInterface.class, argsFromMain);
  String filename = myInterface.getFilename();
  ...
} catch (ArgumentValidationException e) {
  System.out.println(e.getMessage());
}

As a bonus, it even creates it’s own help output from the annotations so you don’t even have to write that (it appears as the message to the exception)!  Overall, I’m quite impressed with JewelCLI; it takes care of the mundane and lets me focus on what is important in my programming.

2012 Goals – December / Full Year Retrospective

And I made it through an entire year of doing retrospectives.  I’m not quite sure what that says about me other than I can write a few sentences on a blog one time a month updating my progress toward goals I have. 🙂

#1 Getting in Shape

I’m getting more in shape. Still need to start jogging again though.  I found some nice exercises about how to fix the computer guy posture that the majority of us all suffer from here.

#2 Propose PhD Topic

I’m ready to go but I’ve run into a few roadblocks and working on getting those resolved.

#3 Learn a New Programming Language

This got put on the back burner for the past few weeks with school taking a priority.

#4 Learn Guitar

I’m still going to lessons but I slacked off a bit on my week off from work to take care of house work that needed to be done.  I picked up an Apogee Jam and Rock Prodigy to help me get better at the guitar.  I’m really liking Rock Prodigy and it’s lessons that you can do while just sitting around the house.  I’m hoping to get back into a schedule where I can do the practice for it at a set time.

#5 House work

This ended up taking some of my time during my holidays to clean up my house.  It’s a lot better than it was before but there is still some more work let to be completed.  I guess this is the joy of home ownership.

Overall

I’m glad I kept this blog up at least chronicling my attempts at New Year’s Resolutions and forcing myself to act upon them, even if I didn’t finish all of them at least I got myself on a track to complete them.

Java Security: The Finalizer Attack

Anyone who is familiar with Java (or other object-oriented) programming has more than likely heard of the SOLID development principles and knows that the O is for ‘Open / Closed Principle.’  In Java the use of the final keyword helps enforce the principle and a second programming ideal discussed in Bloch’s Effective Java book: composition over inheritance.  These two principles most developers should be able to rattle off fairly quickly, however there is a third aspect that the final keyword assists with that not many developers think about.

That is, the final keyword provides is prevention of the finalizer attack.  In short, the finalizer attack is a technique to take over a class through the use of the class’ finalizer method.  Using the final keyword on your class (or the finalize method) prevents classes from injecting malicious code or short-circuiting security routines.

As a note, if you’d like to see more about various secure coding techniques you can read through them here.

Stupid Java Trick: Rethinking how to handle creating the comma-separated list

Everyone knows the simple problem of outputting a comma-separated list.  It’s an easy problem to solve and it’s normally done like this:

int[] ints = {1, 2, 3, 4, ...};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ints.length; i++) {
   sb.append(ints[i]);
   if (i+1 != ints.length) {
     sb.append(",");
   }
 }
System.out.println(sb.toString());

 

And the code will return the following output:

1,2,3,4,....

 

Which is all well and good, however, you normally don’t deal with simple arrays or Lists most of the time, you have to deal with Iterable or you’re using Java’s enhanced for loop.  Neither of these has a way to easily notify the programmer that you’re at the last item in the Iterable.  So how do you take care of this?  Simple, insert the comma before outputting the value.

int[] ints = {1, 2, 3, 4, ...};
StringBuilder sb = new StringBuilder();
for (int i : ints) {
  if (sb.length() != 0) { 
    sb.append(",");
  }
  sb.append(i);
}
System.out.println(sb.toString());

 

And the code returns the exact same output as above.

Nifty little change and you can use with any class that implements the Iterable interface.