Beautiful code from the C++ perspective

Over at Kotaku, there is an article talking about Doom 3‘s source code and how beautiful it is (there has already been an in-depth article talking about the technical aspects of it).  The article is an interesting read since it focuses more on how to format source code than the actual structure of the code itself (not to say they don’t delve a little into what they’ve done technically).  John Carmack himself even chimes in on the discussion talking about the style of coding that he’s beginning to focus on, which is a more functional style of programming.

Almost all the books I’ve seen people recommend about how to code never go in-depth on the stylistic aspects of the language such as where you should put parentheses, how many spaces you should have between lines, how you tab lines and methods and the other minutiea of making readable code.  I suppose you just take up coding like the example code you see.  For me, I try to maintain white spacing and general formatting the same for every language I code in, but then default to accepted naming conventions and such when it comes down to naming variables, methods, classes, etc.

So, my loyal readers (all two of you), what makes code beautiful?

The right solution versus the correct solution

There is a subtle distinction between the two.  Correct implies definitive or absolute whereas right implies an appropriate but still debatable solution. In programming, we run into this problem all the time.  What is the correct solution versus the right solution?  Often times we jump at the right solution instead of thinking about the problem and going with the correct solution.  Then there are times we debate over the correct solution when the right solution would serve perfectly well.

Programming is the art of trade-offs and the right solution versus the correct solution is a perfect example (just read about it here).

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.