Archive for the ‘UI’ Category

TextMate – Introduction to Language Grammars: How to add source code syntax highlighting embedded in HTML

February 8, 2011 7 comments

I’ve blogged about TextMate a few times in the past, and with good reason – it’s an extremely versatile, light weight, powerful text editor for the Mac. One great feature of TextMate is its extreme customizability. Today I’m going to show how to modify one of the TextMate language files in order to add support for Java code within HTML text.

Why is this useful? My workflow for producing blog posts is often to write the post in TextMate using the Markdown markup language, which I then convert to HTML. WordPress has the ability to syntax highlight and provide a nice monospaced version of sourcecode within a post if it’s delimited by <code></code> tags. While the sourcecode comes out fine in the final post, it would be nice to have the syntax highlighting show up from within the Markdown view (i.e. while I am composing a blog post). Let’s get started by looking at how language grammars work in TextMate.

Introduction to Language Grammar Editing

The language support in TextMate is extremely powerful, but it’s a little complicated to get started. In essence, a language defines a series of rules mapping patterns to scopes. For instance, the Java language grammar defines a scope for comments, a scope for control characters, and so on and so forth. The scope is extremely important for many reasons. A few of them are

  • The scope determines whether text is spellchecked or not (a top level scope of source is not spell checked; one that is text will be)
  • It provides syntax highlighting, as certain scopes are associated with certain colors.
  • Snippets can be targeted to only run when within a certain scope. (See this article on Scope selectors for more.) For instance, all the Java snippets are defined as only being active in the scope.

An example of a Java snippet that's only accessible when the cursor is within something identified as

As an aside, you might wonder why the scope is called as opposed to java.scope. The reason is that some scope selectors can target the more general case (scope), whereas those concerned with java can target the more specific scope (java.scope).

Since someone has already done the hard work of creating a language definition for Java and for creating all of the snippets that support it, we want to leverage this body of work. All we need to do is ensure that text between the java tags is considered to be part of the scope, and everything will just work.

First, let us look at a sample grammar file. Open up the HTML language definition file by going to Bundles -> Bundle Editor -> Edit Languages, or via the shortcut ⌃ ⌥ ⌘L, and choose the HTML option. You’ll be presented with a rather inscrutable, unstyled document to the right. The first thing you should do, and which I found out the hard way, is copy all that text and paste it into a new document.

Edit Languages

Edit HTML language

When you paste the text into the document, the text is unstyled and interpreted as plain text. In order to force TextMate to interpret this as a language grammar, you must click the item in the lower middle that says “Plain Text” and choose “Language Grammar” from the dropdown box. The document should look a lot nicer after this step:

Plain Text
After changing to Language Grammar

Take a look through the grammar, but don’t get bogged down in the details. The important thing to look at is the list of patterns defined. Here’s just a small section:

    patterns = (
        {   name = 'meta.tag.any.html';
            begin = '(]*>)';
            end = '(>()';
            beginCaptures = {
                1 = { name = 'punctuation.definition.tag.html'; };
                2 = { name = ''; };
            endCaptures = {
                1 = { name = 'punctuation.definition.tag.html'; };
                2 = { name = 'meta.scope.between-tag-pair.html'; };
                3 = { name = ''; };
                4 = { name = 'punctuation.definition.tag.html'; };
            patterns = ( { include = '#tag-stuff'; } );

This is the first pattern that will attempt to match. You don’t need to understand all of it, but you should understand that the parentheses in the regular expressions denote capturing groups, which are then referenced in the beginCaptures and endCaptures tags. These assign scopes to the various captured groups. Note too that we can recursively include patterns (via the include = '#tag-stuff' line) which assign scope to various parts of the matched text. This allows us to define a pattern one time and reference it in multiple places, which cuts down on code duplications.

If you look through the HTML grammar, you’ll notice that some embedded code is automatically detected and set to have the matching text use the corresponding language:

ruby = {
    patterns = (
        {   name = 'comment.block.erb';
            begin = '';
            captures = { 0 = { name = 'punctuation.definition.comment.erb'; }; };

Here, any times the <%# %> tag pair is seen, the entire block is captured and assigned to the scope punctuation.definition.comment.erb, which has the effect of distinguishing it from surrounding text. You can see this in action in the following screenshot:

comment.block.erb scope

In addition to the fact that the ERB snippet is syntax highlighted, take note of the popup in the screenshot showing “text.html.basic” and “comment.block.erb”. At any point in any TextMate file, you can hit ⌃ ⇧P (Control Shift P) to get the current scope of the cursor. This is extremely useful for debugging why certain elements are not being selected or assigned the scope you think they are.

Adding Java support

While using a TextMate window to edit the grammar is extremely nice, unfortunately you cannot test your changes interactively here. You must copy and paste the contents back to the original grammar window, overwriting the contents, and then press Test. This will reload the grammar and you will see the change reflected in any window using that grammar currently.

With that in mind, let’s add the support for embedding Java within our Markdown blog posts.

The basic pattern is pretty simple:

    {   name = '';
        comment = 'Use Java grammar';
        begin = '\
        end = '\[/sourcecode\]';
        patterns = ( { include = ''; } );
I look for the literal string <code></code> to start the pattern, and then the literal string <code>

to end it. I have to escape the brackets due to the fact that they have a special meaning within regular expressions ([aeiou] matches any vowel, while \[aeiou\] matches the literal string [aeiou]).

By adding this line to the top of the patterns, it is run before any of the others. (Remember, we have to actually add it to the HTML grammar within the Bundle Editor, not just the TextMate window with the grammar inside of it). Once the line is added and you press Test, the Java highlighting beings to work.

Here’s what a snippet of Java embedded in a Markdown blog post looked like without this change:

without language support

And after:

with the language support


Language support in TextMate is a very complex task, and one that cannot be adequately covered in a single post. I’ve shown here how to add a small snippet to the HTML grammar to allow syntax highlighting of sourcecode delimited by special blocks. This technique could be expanded to support any number of other programming languages.

The ability to customize TextMate through editing snippets and language grammars makes it extremely powerful. I hope this has only whetted your appetite to learn more. If it has, please see the macromates site which has more information about this.


WorkFlowy – free minimalist list webapp

January 25, 2011 Leave a comment
Today’s post is about WorkFlowy, a great, free web application for creating and managing lists. It is the best tool for organizing TODOs and random thoughts out of anything I’ve found. 

First, let me describe the two main problems I have with todo/note taking software I’ve tried previously.  Secondly I’ll show how WorkFlowy alleviates these problems.

TODO: fix these problems!

There have certainly been other TODO list applications that I have used in the past, but they usually suffer from at least one of the following problems:

1) They require too much information about each item
When I’m jotting things down, I rarely care about prioritizing it, giving it a due date, assigning it a label, tag, etc.  A lot of organization software hits you over the head with all the different ways to categorize your items; this really can slow you down when you’re just trying to brainstorm in a lightweight manner.  I found Evernote to suffer from this problem.
2) They force you into a flat mode of thinking
When I’m trying to right down all the thoughts in my head related to a given project or task, they often are deeply hierarchical.  I write down task A, which really consists of subtasks A.1 and A.2, where A.2 in turn consists of tasks A.2.i, A.2.ii, and A.2.iii.  I want whatever software I jot down notes with to reflect this way that I think, and it ties into the previous point.  I’d much rather indicate that a task depends on a different task by nesting it beneath another task, rather than manually annotating it with a label.
(Here’s a visual representation of the nested list I described earlier:)
  • A
    • A.1
    • A.2
      • A.2.i
      • A.2.ii
      • A.2.iii
I found Things, a todo manager on Mac to suffer from this problem.  It just didn’t fit into the way I like to jot things down in a nested relationship.


With respect to #1, WorkFlowy is as barebones as you can get.  There are no labels, tags, colors, due dates, etc.  All you do is enter plain text.  If you need all those bells and whistles, then WorkFlowy might not be for you.  But if all you want is an online repository for your random thoughts, I have not found anything better.

Workflow is also excellent at managing deeply hierarchical information, as I described in number two.  It supports the standard tab/shift+tab combo to indent/unindent items.

Indent text with the tab key

Here you see all the top level notes that I have.

Top level lists

Top level lists

By clicking the plus sign to the left of the node, I can expand the subtree that’s rooted at that node.  This allows me to selectively hide/reveal pieces of my lists.

After the chores node has been expanded

The ability to expand/collapse subtrees is nothing new, though it is an extremely useful UI feature (and one that I desperately wish were in Google Tasks).  Workflowy adds an additional way of showing / hiding information, which I’ve never seen before and I wish was copied everywhere.  If you click on the node itself rather than the plus sign to the left of it, you jump to that node in the tree, hiding all siblings and ancestors of that node.  Conceptually, you “zoom in” on that part of your list, ignoring all the distractions of the other lists
Zoom in

Zoom in

You are always able to work your way up the list (backing out of the subtree you entered) through the intelligent use of breadcrumbs that appear at the top of your view.

Breadcrumbs allow you to back out of your current location

This is an extremely effective UI technique, as it allows you to create arbitrarily complex and nested hierarchies but focus on only a small piece of it at any one time.  This allows you to switch between nested and essentially flat views of your data at will, simply by zooming into the relevant portion of the tree and by collapsing the children nodes whose detail you don’t care about.


Workflowy is an extremely lightweight, barebones web application for managing your notes and todo items.  Workflowy encourages you to get down the information as easily and as quickly as possible, and makes it easy to rearrange the data and selectively view the portions you want to see.  It features a unique UI feature for zooming into subtrees of your lists, while providing breadcrumbs to back your way out of your current position.
While I do like the minimalism of the application, there are certain features that I wish were present.  For instance, it would be nice if links were automatically parsed from the plaintext.  Overall, I find Workflowy an indispensable part of my toolkit.

Give an indication of why a button is disabled

December 21, 2010 Leave a comment

In general, it’s a good idea to disable buttons whose functions cannot be accomplished at the given time.  For instance, if you have a table of data and a delete button that deletes the selected row or rows of data, it would make sense to disable the Delete button when no row is selected, and enable it when a row becomes selected.  This is superior to the alternative choice, which is to leave the button enabled and then indicate some sort of error message letting the user know that they can’t delete an empty selection, when they try to press it.

An example of an enabled and disabled button

If you do go down the route of programmatically disabling buttons, it is absolutely crucial that you give some indication as to why the button is disabled.  In the previous example, a savvy user could probably figure out that the delete action doesn’t make sense when there are no rows selected.  This isn’t always the case.
I dealt with an application recently where validation logic was spread across four different tabs, where each tab had a checkmark indicating that it was filled out correctly.  When I finally managed to get all of the tabs to show that they were in a valid state, the final button to complete the action stubbornly remained disabled.  I have no idea what the problem is, and there’s no indication whatsoever in the application.
The easiest thing the programmer could have done to give some feedback to the user is to provide a tooltip on the button that indicates why the button is disabled.  Perhaps a better solution would be to provide a small text pane in which the error messages would be displayed; this has the benefit of working with devices which do not have a mouseover tooltip capability (e.g. iPhone, iPad).
While it would have taken a little more effort on the part of the designer and programmer to make that screen more usable, it would have saved me the past two weeks of trying to solve the problem and waiting for their technical support.  Let that be a lesson for you.
Categories: UI Tags: , , , , – find lighter/darker shades of colors

December 15, 2010 Leave a comment

Color choosers are a dime a dozen online, but is a very nice one.  Its stated purpose is to allow you to specify a color and then find shades that are darker and lighter than that color.  It’s very well designed, aesthetically pleasing, and has the good sense to allow you to copy the hex value of the color with a single click.

I use it on a semi-regular basis to design Java Swing UIs; just a quick tip for the Java folks out there – when you have the hex code copied, you need to preface the hex string with 0x for the Color constructor to work correctly.  In other words, if you are have the hex string #facade, you would create a Java color object with the command new Color(0xfacade).  The 0x tells the Java compiler to treat the following text as hexadecimal.

Categories: Java, UI Tags: , , , , ,

Make your Mac more like an iPhone: How to reduce distractions and improve focus

November 11, 2010 3 comments

While our desktop computers excel at multitasking due to their multiple cores, the human mind fares much worse.  There have been multiple studies showing that multitasking can impair productivity.  Often the reasoning is that the brain requires time to adjust between different tasks, due to the switch in context.  An analogy for this would be driving on a highway.  You’re going to cover a lot more ground in the same amount of time if you can keep a constant speed (focusing on one task) rather than having to constantly take exits and switch to new roads (tasks).  While those who multitask frequently might think that switching tasks bears no greater cost to them than switching lanes on the highway, the studies suggest that the cost in focus and time in switching to the new task is more akin to having to take that offramp, find a new highway, and then get back up to speed.

But enough about metaphors and science.  I am not a cognitive scientist so I’ll leave that up to the people who do it best.  I can only speak for myself, and I find that it’s supremely tempting to pick away at pieces of problems rather than to focus on one thing and make significant progress in that regard.  I also know that I am objectively less productive if I constantly am switching tasks.

It is for that reason that I’ve assembled a set of tools that allow me to have a stronger single-minded focus while working on a computer.  While there are systems such as Getting Things Done and the Pomodoro Technique which address the human aspect, I’m going to be focusing more on technological solutions with respect to working on an Apple computer.  While many criticize the iPhone and iPad for their limited multitasking support, I think having full-screen applications and focusing on one thing at a time is very beneficial.  With that thought in mind, the rest of this post will show various ways to make the Mac less suitable for multitasking and closer to the iPhone/iPad model of computing.

Hide the dock


Gain more desktop real estate.  Eliminate the visual clutter at bottom of the screen.


Right click on a portion of the dock which does not have an icon, e.g. on the portion where the dock can be resized.

Reduce use of tabbed browsing


I love the ability to open multiple webpages in a single browser.  It can be supremely useful when you are researching and need to have multiple pages open to reference.  Unfortunately it can also lead to shallow reading and a mild form of A.D.D. wherein the user (i.e. me) keeps opening new links with the intention of reading them later.  There is seemingly no cost to opening a link in a new tab, but it does exert a cost – it makes it harder to find the tabs that are actually relevant, and it also uses more system memory.


There is a discussion on the Firefox feature request group to limit the number of tabs that one can open at a time, for reasons similar to what I have presented above.  The best solution given is to install a TabCounter extension in FireFox which shows how many tabs you have open.  It still requires you to monitor the number and prune the number of tabs when things get too bogged down, but it’s better than nothing.


For those using Chrome, there is a Tabs Counter plugin which performs the same task.

Hide your desktop icons


My desktop inevitably is the dumping place for miscellaneous junk.  I’d rather just keep it out of sight and search with a program than keep it organized and visually scan through them for what I’m looking for.  Computers are a lot better at search than humans; let’s take advantage of that.  The icons on the desktop do nothing more than distract me.


Camouflage hides desktop icons
+ allows you to double click on the desktop to have a finder window popup for the desktop
+ allows you to change the desktop background
+ free

+ also has option of dimming the menu bar
– paid ($17)

I use Camouflage on both my home and work Mac.  I was happy to see that Windows 7 allows you to hide the desktop icons without installing an additional program.

Dim your menu


Eliminate distractions by de-emphasizing the elements on the screen that are not important.  For the time you are not actively attending to the menu, make it less visually important.

– doesn’t seem to work in 10.5


+ Works fine in 10.5
– abrupt jump between dimmed and not dimmed – the menu dimming in DeskTopple is more gradual / less harsh


Standard brightness


I use MenuEclipse on both my work and home computer.  It’s not a life changing application but it does what it sets out to do.

Dim your unused applications


When you have multiple applications jockeying for your attention, you necessarily lose focus

There are some obvious exceptions to this; for instance it is often extremely convenient to have both a calendar program and e-mail program open side by side when scheduling things, or having a web browser next to your programming environment for web search results.  There are other times in which such extra programs are a distraction; in this case having a single program as the focal point can allow you to focus.


+ free
– does not interact correctly with Quicksilver/Alfred quick launchers
– noticeable lag when switching between windows
– no way of specifying the brightness
– seemingly not in active development
– Ugly icon that takes up a huge amount of space

+ Free
+ Much more polished than DooDim
+ Allows you to customize how dim the background gets
+ System settings stay bright
+ Works with Quicksilver/Alfred

O different interface than Doodim – you have to explicitly choose a new window to focus on via an interface similar to the standard task switcher, rather than being able to shift the focused window by clicking on other windows.

– Does not work with multiple spaces

I use think on a daily basis; in fact I am writing this article with all but my FireFox window dimmed out.  The higher your screen resolution, the more useful this program is.  When working on a 13″ screen I don’t often tile my windows too much.  But when you have a 30″ monitor or something similar, you can end up with many programs onscreen simultaneously.  And you might not want to put the program you’re working on full screen, especially if it’s just a text editor.  That’s when being able to have your programs the size you want and still be able to dim all the rest can be especially useful

Eliminate interruptions

The final piece in reducing distractions and improving single-minded focus is to remove the interruptions that our installed programs produce.

Turn off Growl notifications

If you’re unfamiliar with Growl, it’s a program which ” lets Mac OS X applications unintrusively tell you when things happen. ”  While it is a lot less intrusive than a traditional modal popup window, it still can be distracting.  The first thing you should do is close the programs that are creating the popups in the first place, but you might want the program to run, just not keep interrupting you.

I personally haven’t taken this step, but you can remove Growl if you find it too distracting.  Instructions are here.

Turn off e-mail alerts

E-mail clients on the Mac seem to think every e-mail that comes in is a matter of life and death, and that you absolutely must see every e-mail the instant it arrives.  Those of us who work in an office know that this is far from the truth.  As Merlin Mann writes:

Email is such a funny thing. People hand you these single little messages that are no heavier than a river pebble. But it doesn’t take long until you have acquired a pile of pebbles that’s taller than you and heavier than you could ever hope to move, even if you wanted to do it over a few dozen trips. But for the person who took the time to hand you their pebble, it seems outrageous that you can’t handle that one tiny thing. “What ‘pile’? It’s just a fucking pebble!”

While dealing with e-mail is a whole different issue, the least we can do is make sure that each pebble falls silently into the inbox rather than calling attention to itself.

Mail -> Preferences -> New mail sound: None



How to turn off e-mail notifications in Entourage
Short version:
Entourage -> Preferences -> General Preferences -> Notification ->
Uncheck Display Alert, Bounce Icon, Bring Application to Front, and New Mail Sound


Instructions on turning off e-mail notifications in Thunderbird


This post was started long before Apple’s announcement of its new operating system, Lion, but it was not surprising to me that Apple is going to make OSX work more like iOS, with the addition of full screen applications and an app store.  I don’t want the Mac to become exactly like a giant iPhone or iPad, and I certainly wouldn’t want every application to be full screen.  However, there are times when I need to focus, and by making the computer less capable, it makes me more.

Improve web readability with … Readability

October 28, 2010 1 comment

Original article

After a pass through Readability

After a pass through Readability

arc90 has a free service called Readability which is invaluable for reading articles on the web.  In a nutshell, it strips out all the extraneous content on a page and presents just the main article text, in a beautifully formatted way.  You can configure the way the final page is rendered using the previously linked page, with such options as margin width, text size, the ability to convert hyperlinks to footnotes to avoid distraction, and a few different typographical options.  Once you’ve done that, you merely drag button up to your bookmarks as a link; whenever you’re on a page that’s overly busy, you just choose that bookmark and the page instantly converts to a more readable document.

Readability options

Readability options

The one drawback I’ve found is that nicely formatted code in an original document does not come out that way in the Readability version.  Still, if what you’re reading is not full of source code, this site is absolutely vital.

Categories: UI Tags: , , , ,

Java: Creating correct equals and hashCode methods

August 24, 2010 11 comments

Equals and hashcode

Generating correct equals and hashCode methods is hard. There’s an entire chapter or two devoted to it in Joshua Bloch’s Effective Java, a definitive tome for Java developers. Getting these two methods correct is important if you’re going to be using your domain objects within Java collections, particularly hash maps.

As manually generating equals and hashCode methods is difficult and error prone, there are a few different techniques for helping the developer with the process.

We will be using the following simple class to explore this issue:

public class Point {
    private int x;
    private int y;

    public Point(int x, int y) {
      this.x = x;
      this.y = y;

    public int getX() {
      return x;

    public int getY() {
      return y;

Library based solution

There is at least one library that supports the generation of equals and hashCode methods, and that is the excellent Apache Commons Lang. There is a good explanation of how to use it here, but here’s a condensed version, from the javadocs with my annotation added in the comments:

// Nick: An example using reflection to determine all of the fields of the object;
// easiest to use but as it uses reflection it will be slower than manually
// including the fields
public boolean equals(Object obj) {
   return EqualsBuilder.reflectionEquals(this, obj);

// Nick: An example explicitly choosing which fields to include within the EqualsBuilder
// Note that it still requires some knowledge of creating correct equals methods, so it's not as idiot proof as the previous method
public boolean equals(Object obj) {
  if (obj instanceof MyClass == false) {
    return false;
  if (this == obj) {
    return true;
  MyClass rhs = (MyClass) obj;
  return new EqualsBuilder()
                .append(field1, rhs.field1)
                .append(field2, rhs.field2)
                .append(field3, rhs.field3)

The HashCodeBuilder works similarly:

public class Person {
   String name;
   int age;
   boolean isSmoker;

   public int hashCode() {
     // you pick a hard-coded, randomly chosen, non-zero, odd number
     // ideally different for each class
     return new HashCodeBuilder(17, 37).

   // Nick: Alternatively, for the lazy:
   public int hashCode() {
      return HashCodeBuilder.reflectionHashCode(this);


Using the library is a good approach, but it also introduces a dependency that may not be otherwise necessary. There are a lot of good classes in Apache Commons Lang, but if all you are using it for is the EqualsBuilder and ToStringBuilder, you’re probably better off avoiding the dependency. In this case, you can make your IDE do the heavy lifting for you.

IDE based code generation

Given that IDEs like NetBeans and Eclipse do such a good job of automatically creating things like getters/setters, constructors, etc., it’s no surprise that they can be used to generate equals/hashCode methods as well. Unfortunately, they are not perfect, which prompted me to write this post in the first place.

I will be focusing on NetBean’s implementation of the equals/hashCode code generation as of version 6.9 (the most recent version).

When you are in NetBeans and press Ctrl+I, the IDE provides a popup menu with options for methods that it can automatically generate for you.

Generate options in NetBeans 6.9

When you choose the equals() and hashCode() option, you are presented with the following screen (where the variables will differ depending on your class, obviously).

equals() and hashCode() generation dialog

After checking all of the checkboxes and pressing generate, the IDE inserts the following two snippets of code:

public boolean equals(Object obj) {
    if (obj == null) {
        return false;
    if (getClass() != obj.getClass()) {
        return false;
    final Point other = (Point) obj;
    if (this.x != other.x) {
        return false;
    if (this.y != other.y) {
        return false;
    return true;

public int hashCode() {
    int hash = 3;
    hash = 97 * hash + this.x;
    hash = 97 * hash + this.y;
    return hash;

Perfect. Great. The IDE has done all the work for you. It’s definitely more verbose than the Apache Commons solution, but at least there are no dependencies introduced into your code. If you change your class so as to introduce more variables you wish to consider for equality and hashCode, you should delete the generated methods and regenerate them.

While this is functional, there are two main problems I have with this dialog:
* Multiple checkboxes
* No linkage between equals/hashCode

I will address each in turn

Multiple checkboxes

There is no means for enabling or disabling all of the fields. Any time there are (potentially) a lot of checkboxes, you should give the user the option to toggle them all at once. You can that the NetBeans designers did just this in the Generate Getters and Setters dialog in NetBeans 6.9.

Generate getter / setters

Here you can see a checkbox next to the Point class name which toggles all of the children nodes’ checkboxes (all of the variables). This is pretty standard UI stuff; here is this pattern at work in GMail and Google Docs.

GMail's select/deselect options Google Doc's select/deselect

This is not the end of the world, as the dialog does support keyboard navigation and toggling of the check boxes via the space bar. It is a bizarre UI feature though, as there is absolutely no indication as to which of the two panes has focus, and thus which checkbox you’re about to toggle. By the fact that I’m familiar with focus traversal, I intuited that tab would shift the focus between the panes but there’s no way a novice would know that and no indication of this. In the following screenshot, note that it’s impossible to tell whether I’m about to toggle the x or the y variable.

What will happen when I press space?

Lack of coupling between the equals/hashCode methods

Usually coupling is considered a bad thing in programming. However, when creating an equals and hashCode methods, it’s vital that the same fields be used in the construction of both methods. For instance, if you use a variable x and y to create the equals methods, you should use exactly the variables x and y while constructing the hashCode method.


This post from does a good job of explaining this:

Overriding the hashCode method.

The contract for the equals method should really have another line saying you must proceed to override the hashCode method after overriding the equals method. The hashCode method is supported for the benefit of hash based collections.

The contract

Again from the specs:

  • Whenever it is invoked on the same object more than once during an execution of an application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.

So equal objects must have equal hashCodes. An easy way to ensure that this condition is always satisfied is to use the same attributes used in determining equality in determining the hashCode. You should now see why it is important to override hashCode every time you override equals.

That sentence from the last paragraph sums it up: “An easy way to ensure that this condition is always satisfied is to use the same attributes used in determining equality in determining the hashCode”. Thus it’s clear that the dialog should provide a linkage between the equals/hashCode columns such that toggling the row of one column toggles the corresponding row. Otherwise you can create situations that are guaranteed to violate the contract of equals/hashCode, nullifying the entire point of having the IDE generate these methods for you.

For instance, see the following screen shot:
Violation of contract, allowed by the GUI

The dialog will allow you to continue, blithely creating the erroneous methods, only to manifest itself as subtle bugs later, with no warning. Either the dialog should force you to choose the variables in tandem, or at the very least it should offer a warning that choosing mismatching variables for the equals and hashCode methods can introduce bugs into the program.


I’ve investigated two ways of freeing the developer from the burden of implementing a correct version of equals and hashCode, through the use of Apache Commons Lang and NetBeans IDE. I’ve also detailed problems in the UI design of the dialogs presented for the generation of these two methods from NetBeans.

Thanks to Daniel for bringing Eclipse’s dialog to my attention. Eclipse's dialog
As you can see, they do not separate out the equals/hashCode, which makes a lot more sense to me.