Programmer tools of the trade

Tools of the trade for a Programmer are many. Everyone thinks of the computer, the language, various frameworks, and possibly an IDE. Fewer think about the keyboard and pointing device they use, and even fewer would consider the desk or chair they’re using as tools of their trade.

But think about it a moment. We’re in front of our computers at least 8 hours per day. Are your back, posterior and fingers not worth considering?

I’ve been complaining about the chairs my employer provides for several years now. Every time, I was told the chairs were fine, as long as they were adjusted correctly, and besides, I was the only one complaining. I had spoken with several co-workers, and they either had no opinion (the minority) or also felt the chairs provided are inadequate.

Recently, I had the opportunity to use the infamous Aeron chair for several months. Here was the proof I was looking for that a good chair is not only available, but much nicer and more relaxing to use on a daily basis. As I recently returned to my employer’s office, I had a decision to make live with the chairs, or buy myself a chair.

Of course, I once again started by requesting a better chair, but once again, my request fell on deaf ears.

So, I purchased a chair for myself. I considered the Aeron, but a new chair from the same company has been released, so I wanted to try it first. I found a local store that carried the chairs, and after 15 minutes, I was convinced that the new design was definitely a step forwards.

I have been using my Embody chair for the last 2 weeks, and have no regrets about the purchase. Yes, I could have gotten a used Aeron for significantly less, but I honestly think the Embody is that much better. Also, as the chair has a 12 year warranty, I expect I will still be using it 20 years from now, so amortized over that amount of time, the chair isn’t that expensive.

The difference is surprising. Just today, I sat in one of the company chairs, and couldn’t believe it took me this long to get a better chair. Well worth investigating, and investing.

Inline Construction of Static Lists (and other classes)

I’m sure you’ve seen this form of initialization many times

public static final String[] SOME_ARRAY = new String[] {
    "value1",
    "value2"};

but what if you want to have lists? or you want to have a list that builds upon another list?

Then odds are this is what you’ve written:

public static final List LIST1;
public static final List LIST2;
{
    LIST1 = new ArrayList();
    LIST1.add("value1");
    LIST2 = new ArrayList();
    LIST2.addAll(LIST1);
    LIST2.add("value2");
}

an alternative way to write it is this:

public static final List<String> LIST1 = new ArrayList<String>()  {{
     add("value1");}}
public static final List<String> LIST2 = new ArrayList<String> {{
     addAll(LIST1);
     add("value2");
}}

Personally, I think the above is cleaner, and easier to follow, so if you agree, consider using it the next time you want this type of construct.

To explain what’s happening here, basically, you are constructing an anonymous subclass of ArrayList, and whatever is inside the nested {} is the constructor.

You could, although I wouldn’t recommend it, do something like this:

    public static final List<String> LIST2 = new ArrayList<String> {
        private Long someField;
        public Long getSomeField() { return someField; }
       ....
       {
           addAll(LIST1);
           add("version2");
      }
    }

One place where this syntax is put to use is JMock2 and construction of it’s expectations.

TortoiseHG Version 2.0 Released

The next version of TortoiseHG has been officially released. This release is a major upgrade from the previous version.

With version 2, the primary focus was creating an integrated workbench for dealing with Mercurial. I have been using the pre-release version for several months, and am quite impressed. Everything starts and ends at the workbench screen. The flow of operations is well handled, and gives you options when something needs to be handled.

An example would be a merge. With the previous version, if you had outstanding local changes, the merge dialog would merely throw an error, and you’d have to close the dialog, and do whatever you wanted to do about the local changes.

In Tortoise 2.0, the dialog reports that you have outstanding local changes, and gives you several options. Lose changes, shelve (temporarily store) the changes, see the changes. The choices you would make.

Once you make a decision (all from the merge dialog), the dialog updates, and will allow you to continue.

For merging files, you now have the option to explicitly do manual resolving on all files, or allow Tortoise/HG to do the usual auto-resolve. If you choose manual, then there’s a new dialog that shows all the files that haven’t been resolved, and those that have. The common options are all there, and one can easily re-do a merge.

The list goes on and on as far as improvements, so review the release notes.

The only ‘problem’ with this release is there is a learning curve when starting to use it. Things are not in the same place as the old version, so it will take some time to get comfortable with the new look and operations, but I think it’s well worth the effort.

I think this will be a huge boon for HG.

TortoiseHG is available for Windows and Linux. There is also a port for OS/X, but I don’t know what state it’s currently in.

Eclipse and Opening Implementation of an Interface

As a Java dev, a lot of code implementation is done against interfaces. In Eclipse, F3 goes to the definition of an interface.

In previous versions of Eclipse (3.2/3.3/3.4 era), I would always install the implementors plugin which added Alt-F3 as an ‘open implementation’ shortcut.

In Eclipse 3.6, this functionality is now built-in. If you ctrl-click on a method, it pops up a dialog asking if you want to open the implementation or the definition.

If you goto preferences…keys, and filter by ‘open i’, there will be an open implementation option. Assign it to whatever key you want (I use Alt-F3 due to familiarity with Implementors). Now, if you press F3, it will continue to take you to the definition. Alt-F3 will now take you to the implementation. Open implementor works regardless of whether you’re in the interface definition, or on a caller of the method.

Eclipse Package Name Shortening for Display

Just read about this feature here. Basically, allows you to use pattern matching to shorten the name of packages that appears in the package explorer.

There are 2 options here. The first is to compress the package names.

As per the dialog, if you type some text (other than a number) as the pattern, each level will display that text instead.

So, given org.eclipse.jdt, and entering text a_, it would display as a_a_jdt.

If you put a number in the list, it will show that many leading characters.

So, if you put 1, you would see oejdt. If you put 1., you would see o.e.jdt.

The second feature is to abbreviate package names. In the dialog, enter the portion you would like to substitute a shorter name for, and provide the replacement text.

e.g. org.eclipse=oe, and you would see oe.jdt.

The 2 rules can be combined, so if you had the package org.eclipse.jdt.compiler and had a pattern of 1., and an abbreviation as above, you would see oe.j.compiler.

Eclipse Debug Filtering

If you use AOP, hibernate and various other projects, and you’re debugging in Eclipse, I’m sure you’ve encountered this scenario.

You hit F5 (step-into) and end up in an interceptor, which leads to another and another, and eventually you get to the line of code you actually want. Of course, I could open the file I want and do Ctrl-R (run to here), but if I forget… plus it’s extra work.

The other place is in a method, and wanting to return. Press F7 (Step Return) and end up walking back through all the interception code.

Well, Eclipse has an ‘answer’ for this. They’re called Step Filters, and can be found in preferences, Java/Debug/Step Filtering. You will likely already see some entries here, but feel free to add whatever packages/classes you don’t normally want to see when debugging. I’ve added things like:

  • org.apache.commons.logging.*
  • org.springframework.aop.*
  • org.springframework.jdbc.*

etc. I could have just added org.springframework.*, but wanted to be more specific.

Then, when debugging, ensure that Step Filtering is activated (available in the preferences, but also an icon in the Debug Perspective. Now when you do step into, step return etc, the items you’ve requested to be filtered out will be.

One thing I’ve noticed. On the preferences dialog, when you choose Add Packages…, be patient. It takes Eclipse awhile to build up the list of packages to select from, but I think it’s worth the wait…

Static Typing Doesn’t Mean Giving Up Open Classes

In Groovy (and other languages that support meta-programming), one can extend the functionality of existing classes to provide powerful functionality. Here’s a simple example in Groovy.

Integer.metaClass.daysAfterToday = { ->
  Calendar today = Calendar.instance
  today.add(Calendar.DAY_OF_MONTH, delegate)
  today.time
}

// now can use this syntax anywhere after the metaClass modification
5.daysAfterToday()

The above code adds a new method, getDaysAfterToday to an Integer. As you can see, it will return the date that is 5 days after today (hence the name).

Something similar can be accomplished in Scala via implicit conversions. Here’s the code.

class DateHelper(days:Int) {
  def daysAfterToday():Date = {
    val today = Calendar.getInstance
    today.add(Calendar.DAY_OF_MONTH, days)
    today.getTime
  }
}
implicit def Int2DateHelper(days: Int) = new DateHelper(days)

// now we can use this syntax anywhere the implicit conversion is defined
5.daysAfterToday

So, what does the Scala code do?

  • Defines a class that has a constructor that takes an Int. This will also create a property called days
  • Define a method daysAfterToday that returns a Date that is ‘days’ days after today.

The line beginning with implicit is the interesting one. It defines a conversion from Int to DateHelper.

So, the compiler will then see the 5.daysAfterToday. As 5 is an Int, it will try and find a method daysAfterToday on Int. Obviously it doesn’t exist. So, it will then start examining all implicit definitions that are in scope (as implicits have a lexical scope. They would generally be associated with a package, and imported accordingly).

The compiler will eventually ‘find’ the Int2DateHelper implicit definition, and modify the 5 to be a DateHelper object. Then when that line of code is executed, it will actually be calling daysAfterToday on the DateHelper object.

So, the same syntactic sugar can be used when defining a DSL or any other type of coding. Of course, you also now have the compiler doing some testing for you, as it will complain if it can’t find an implicit conversion.

In contrast, it’s up to the developer to test their code thoroughly to ensure that all places where daysAfterToday is used actually work correctly. For example, if I wrote the following in Groovy

Long someLong = 10:
someLong.daysAfterToday

The dev wouldn’t find out until run time (or hopefully in the test the dev wrote around their code) that daysAfterToday is not defined for a Long.

If a developer does something similar in Scala, the compiler will tell them that ‘daysAfterToday is not a member of Long’, and no explicit test is required.

Java vs Groovy vs Scala: A Simple Example

I’m in the process of learning Scala, and find it interesting to contrast the 3 languages of the title. Java is Java.

Groovy, at least in my mind, is a nicer Java. Cleaner syntax, with more commonly done functions built-in. Also, not too hard to learn if you already know Java. With a few exceptions, you can write Java code, and the Groovy compiler will know what to do with it. Once you learn some Groovy features, you can start taking advantage of them.

Groovy also adds dynamic and meta-programming abilities, which are very powerful features, and can make development quicker. Just make sure you write lots of unit tests.

Scala on the other hand is a new animal. It’s still a JVM language, but is trying to address the weaknesses of Java, provide dynamic typing development speed, and still remain statically typed.

Two things in Scala really help with the above. One is type inferencing, and the other is being able to define types.

One of the biggest complaints about Java is the amount of typing required for defining items, especially when Generics are involved. For example:

// Java version
List<String> myList = new ArrayList<String>();
myList.add("some value")
//Scala version
// Note: Scala uses [] rather than <> for generics.
// < and > are valid in Scala method names, so can't be used in definitions.
val myList = new ArrayList[String]
myList.add("some value")
myList add "some other value"

// of course to make it truly Scala, it would become:
val myList = List("some value", "some other value")

The end result is the same. Both myList will be ArrayLists of String, but much less typing required.

Scala also allows something akin to duck-typing. It isn’t duck typing, but it does allow one to not have to define interfaces on a number of Objects that will be used in a method.

// Java
public void testMethod(IOutputable someObject) {
  someObject.output();
}
// Groovy
def testMethod(someObject) {
 someObject.output() // may throw a MissingMethod exception at runtime, so make sure you test
}
//Scala
def testMethod(someObject:{def output()}) = {
  someObject.output()
}

The above method will take any object that has an output() method defined on it. So, you don’t have to define an interface with an output method on it to pass objects in, but the compiler will also have an error if the testMethod is called passing an object that doesn’t define an output method.

The syntax of Scala will seem weird to a Java developer. There are a number of conventions to get used to, and various other ‘oddities’ about the language that take time to get used to. Here’s an example of the same functionality in all three languages.

//Java - what we're used to seeing
public String buildEpochKey(String... keys) {
  StringBuilder s = new StringBuilder("elem")
  for(String key:keys) {
    if(key != null) {
      s.append(".")
      s.append(key)
    }
  }
  return s.toString().toLowerCase()
}
//Groovy - still fairly straight forward to see what's happening.
// NOTE: .with {} means that any method calls in the curly-braces will be called on
// the object before the .with.
// i.e. addAll, retainAll and join will be called on keys2
def buildEpochKey(String... keys) {
  def keys2 = ["elem"]
  keys2.with {
    addAll(keys)
    retainAll{it != null}
    join(".").toLowerCase()
  }
}
//Scala
// - in the method definition, keys is the variable.
// String* is like Java's String...
// the : after the parenthesis with a type defines the method return type (i.e. String in this case)
def buildEpochKey(keys: String*): String = {
  ("elem" +: keys) filter(_ != null) mkString(".") toLowerCase
}

What was that?!?

  • +: means add the item before the +: to the item after it
  • filter filters a collection based on the closure after it. Filter will pass each item into the closure. If the closure returns true, the item will be added to the new collection, otherwise it won’t.
  • _ in a closure is a shortcut for saying the first parameter passed in
  • mkString is Scala’s version of join. mkString also has a variant that takes delimiters.
  • toLowerCase is just that. A call on the string that is the result of mkString

I suspect the Java code is the most efficient of the 3, as it only loops through the items once. Don’t know if Groovy or Scala are able to optimize away the multiple iterations. And, it’s possible this could be written more efficiently. After all, I’m relatively new to Scala and the whole functional development thing.

So, as you can see, Scala can allow you to be very succinct with the code you write, but it certainly takes some getting used to. Also, I’m finding the Scala IDE plugin for Eclipse is only ok. It allows for debugging, and some basic refactoring, but it seems somewhat slow right now.

It is being improved all the time, but as there isn’t a lot of boilerplate code to type with Scala, I’m not minding the plugin weaknesses that much.

As far as resources for learning Scala, I’m currently reading 2 books. One is Programming in Scala 2nd Edition, and the other is O’Reilly Programming Scala. Programming in Scala 2nd Edition was just released, so it covers all the features added in Scala 2.8.1, and the O’Reilly book appears to be updated when new language releases are made. I can’t find a link to the downloadable PDF for the O’Reilly book, but I was able to find one Googling around.

Next Release of TortoiseHG

I’ve started using the next release version of TortoiseHg 1.9. Two major things are happening.

The less interesting from a user perspective is the switch from the PyGtk UI library to the PyQt library.

The more interesting one is the introduction of a workbench. The 1.8 and prior versions didn’t have one location for doing everything from. If you wanted to browse your history and changeset graph, you used the repository explorer. When it was time to commit, a new dialog opened (accessible by toolbar buttons), but it didn’t close afterward.

After some usage, it wouldn’t be surprising to see a number of windows open for various tasks.

The 1.9 release now has the workbench. The individual dialogs are still available, and the distinct functions still appear on the Explorer context menu, but I find myself always working in the workbench.

Multiple repositories can be open at once, shown via tabs. All the functions you want to do are easily accessible within the workbench.

When it’s time to do a merge, it’s much smarter. In the old version, if you had uncommitted changes, it would warn you, but provide no options.

The new version warns you, but from the dialog gives you all the options you could reasonably want. Discard current changes. Shelve changes. Force a merge on top of changes etc.

Another area that is drastically improved is around merge conflict handling. The previous version would do an auto-merge always, and only prompt you if there were conflicts not handled.

The new version allows you to disable/enable auto merge right in the merge dialog. If you select ‘manual’ merge, then it will let you know there are conflicts that need to be resolved. A new dialog is available, and from there, you see all the files that had conflicts, and then on a file by file basis, you can decide to do an auto merge, manual merge, take left or take right.

There are many additional workflow improvements in this release, and I’m confidently using it right now. The biggest thing to be aware of is it’s built against the latest Mercurial, so if you can’t run the latest Mercurial, I wouldn’t suggest trying it out.

I’ve even started doing some contributing by reporting issues, and suggesting enhancements. If I knew Python, I’d be attempting to contribute code as well, but…

Google Becomes a Java Developer’s Best Friend: Instantiations Developer Tools Relaunched for Free

I hadn’t heard of Instantiation but others had. Looks like their tools are very powerful, and after acquiring them, Google has made them available for free.

A couple links in the attached article didn’t work, but I could definitely get to the CodePro Analytix site and have installed the plugin.

The tools include a GWT GUI designer, code analysis/coverage/JUnit test generator, UI Test automation tool and general UI designer.

Google Instantiation tools

Java: Retrieving String Representation of an Enum Value

If you have an enum defined as such:

public enum myEnum {
   VALUE1,
   VALUE2
}

and you want to convert it to string values of VALUE1 and VALUE2 for use elsewhere, there are 2 methods available. name() and toString().

If you want to always be guaranteed that you get VALUE1 and VALUE2, you must use name(). toString() can be overridden, and depending on the enum, is likely to be.

For example, if we modified an enum to contain properties, we might want toString to reflect this.

public enum Planets {
   MERCURY("first"),
   VENUS("second"),
   EARTH("third")

   private String positionFromSun;

   public Planets(String positionFromSun) {
      this.positionFromSun = positionFromSun;
   }

   @Override
   public String toString() {
      return "The planet " + this.name() + " is the " + this.getPosition() + " planet from the sun";
   }

name() for the above enum would still return MERCURY, VENUS and EARTH whereas toString() obviously will not.

Eclipse Debugger Won’t Find Source

Just had this problem. Run my server external to Eclipse, and use a debug connection.

Breakpoint set, but when stops, Eclipse complains can’t find source.

Clicking the ‘edit Source path’ button, I could see the source folders there. Eclipse would flash the source code, and then very quickly go to the ‘source not found…’.

Finally modified the paths. Rather than using explicit folders, I removed all the folders, and did add project… This appears to be what Eclipse requires.

Documenting for others that have run into it, and for myself the next time I experience it, and have forgotten what I did to fix it…

Toyota’s Software Development Practice Not as Advanced as It’s Manufacturing

In a blog post titled Toyota’s journey from Waterfall to Lean Software development, Henrik Kniberg describes his visit to Toyota in April 2009.

It appears they were using waterfall, and had only begun investigatin the pros and cons of Agile.

We look to their manufacturing side for insight into Agile software development, and yet they aren’t doing that themselves. Very interesting.

It appears they’re finding the waterfall process doesn’t work for them (I doubt any of us are too surprised), and they’re investigating other options.

Perhaps this explains some of the issues we now see with software in cars…

Mercurial Tutorial

A reasonable starting point for understanding the basic concepts behind a DVCS, and Mercurial in particular.

The only thing is you have to get past the sense of ‘humour’ of the author, but the content is good.

A Mercurial Tutorial

The project I’m working on has gone with named branches for branches, and therefore one repository, rather than what seems to be the generally accepted approach of copying the repository, and then pulling changes from the old one.

The end result is basically the same, but without the ‘baggage’ of named branches. Personally, I prefer being able to see a branch with a name, and knowing what it’s associated with.

The other decision we’ve taken is to generally use rebase, rather than pulling others changes, merging them together, and then pushing. The only real reason is it keeps the number of changesets down (no merges everytime I have changes and someone else has already pushed), and also keeps the branch in the graph straighter/cleaner.

Mercurial server on windows IIS

http://vampirebasic.blogspot.com/2009/06/running-mercurial-on-windows.html

http://stackoverflow.com/questions/818571/how-to-setup-mercurial-and-hgwebdir-on-iis

Good starting point. Comments mention in order to push, have to create windows user, and add them to push list.

A Little Groovy Goodness

Ever since attending the SpringOne 2GX conference, I’ve been intrigued by Groovy. I’ve finally had a bit of time to start working with it, and decided to share some of the niceties of Groovy. This post is a very simple example of the differences in coding between Java and Groovy, so expect to see more as time, and my knowledge permits.

The first thing I really liked about Groovy was the removal of explicit setters and getters. I’ve always hated the clutter, and especially since it makes it harder to see if any getter/setter is doing something ‘special’, or if there are methods that aren’t setters/getters.

So, a simple bean defined like so in Java to support easier setting of variables

public class Bean {
    private long numberOfCompanies;
    private long numberOfUsersPerCompany;
    private long numberOfSecureMessages;

    public long getNumberOfCompanies() {
        return numberOfCompanies;
    }
    public Bean setNumberOfCompanies(long numberOfCompanies) {
        this.numberOfCompanies = numberOfCompanies;
        return this;
    }

	// code snipped here
}	

//used like this
    growthRequest
       .setNumberOfCompanies(1L)
       .setNumberOfUsersPerCompany(1L)
       .setNumberOfSecureMessages(2L);

becomes this in Groovy

public class bean {
    long numberOfCompanies
    long numberOfUsersPerCompany
    long numberOfSecureMessages
}

 // and gets used like this
growthRequest.identity {
   numberOfCompanies = 1L
   numberOfUsersPerCompany = 1L
   numberOfSecureMessages = 2L
}

// or like this, without defining a constructor...
	GrowthRequest gr = new GrowthRequest("numberOfCompanies:1L", "numberOfSecureMessages:2L", "numberOfUsersPerCompany:1L")

Groovy also supports the concept of a read-only property. It uses the final keyword, which is a little confusing to us Java devs, as the field isn’t final in the Java sense. A getter will be defined in the public interface of the Groovy object, but the object can still modify the value internally.

Another case that is very nice is long strings, or strings that are concatenated with variables. In Java, we have

String s = "some text that is long " +
	"and some more text that goes here" +
	someVar + " more text and more";

whereas Groovy would have

String s = """some text that is long
	and some more text that goes here
	${someVar} more text and more"""

If your string is just a regular string (i.e. no variable replacement), you can use apostrophes. If you use a single quotation mark, or triple quotation marks, then Groovy will parse the string to search for replacements. So, for performance reasons, unless you need a variable replacement, use apostrophes for strings.

The heredoc format allows for much easier test string generation. For example

String s = """
	<xml>
		<entities>
			<entity>1</entity>
			<entity id="idValue">2</entity>
		</entities>
	</xml>

Keep in mind that I’m intentionally typing variables. Groovy allows for no typing as well, so the previous example could merely def s.

TortoiseHg – The Next Version

It is available from here. From the downloads.

The latest will always be marked as unstable, as it’s still being worked on, but I’ve been using it the past month or so with no issues. Some features are hidden, or have been moved, but the pace of development is very good.

The nicest thing is the integration. Everything can be done from the workbench, and an action flows nicely through a set of dialogs, and ends up at the workbench.

Multiple repositories can also be opened.

An example of the nice touches. This morning, I did a fold. Up pops a dialog with the merged commit message, a list of the patches being folded, and a checkbox to control whether the patch files are kept afterwards. Modify the commit message and press finish. All in one step.

Another major addition is around the patch queue, and its functionality. In the past, if you wanted to move a file from one patch to another, it involved a few obscure, and potentially dangerous commands.

Now, there’s an integrated MQ manager. It allows for easy movement of files from one patch queue to another, but ALSO allows for movement of portions of a file from one changeset to another.

So, if you do a refactor, and then start on other work, but have it in one patch, you can now create 2 patches out of it. Personally, I like to commit refactors and actual new dev work separately, and with the new MQ utility, this is feasible.

Bottom line, if you’re using HG, checkout the new workbench.