The Compulsive Coder, Episode 4: You Create, It Assigns

roomba long exposure
Image courtesy Chris Bartle. License.

Some languages are destined to be always overly verbose. One feature I’d hoped for in later versions of Java was implicit typing. In C#, for example, you can declare:

var customer = new Customer("Jose Cañusi");

It’s not too hard for the compiler to figure out that customer is of type Customer.

Java still has no implicit typing. Any time you need a non-specific Customer instance, you need the following code:

Customer customer = new Customer("Elmer Sklue");

I’m out of breath doing all that typing! Well, not really: I didn’t do all that typing. But I’ve suppressed a scream too often pairing with folks who do type the word customer three different times.

We have computers to compute for us. Never mind that the Java language is a cranky old uncle, you at least have a Generation Z development environment if you’re using Eclipse or IDEA.

I’m pretty sure I first saw J.B. Rainsberger demonstrating the following tip at least a dozen years ago.

Type the instantiation (right-hand) side of things first:

new Customer("Anne Teak");

Do not type the left-hand side! Instead, press Cmd-1 (Quick Fix; the corresponding keystroke is Alt-Enter in IDEA). Select Assign statement to new local variable and press enter. If you’re young enough to store away another shortcut, use the slightly more effective Cmd-2-L key combination instead.

Unnecessary typing represents distraction, waste, and risk.


Previous Compulsive Coder blog entry: Typing Isn’t the Bottleneck
Next Compulsive Coder blog entry: Extract Method Flow

The Compulsive Coder, Episode 2: Syntax Coloring

eclipseColorWheelNote: I understand that not everyone sees the entire spectrum of color. This blog post is focused on those who are able to clearly distinguish color differences. Perhaps my sentiments and suggestions apply to other visual triggers, which as I understand still exist for many of those diagnosed as color blind.

In 1986, my manager broke down and bought me my very first color monitor–a good deal more expensive than a monochrome monitor. I still remember him saying, “What a waste. What do you need those colors for?” I didn’t have much of an answer other than that it was “easier on the eyes.” Mind you, this is in the days where most software was geared for of 25×80 character-mode, green-on-black terminals. I hooked into an HP/3000 minicomputer, and the OS (MPE-III) wasn’t going to cough up anything particularly interesting with respect to colors.

Today, we take color for granted on our phones and other devices, and know how colors play a significant role in garnering attention and triggering reactions.

And yet. At a customer site where developers code using Eclipse, a first glance tells me that virtually all programmers accept the default color scheme provided; no questions asked. Sigh.

What do Eclipse default colors look like? Take a look:

eclipseBlah

Pretty uninteresting, eh? Black, purple, blue. Neither panache nor nuance. Nothing really stands out.

In fact, Eclipse emphasizes the wrong things. Keywords such as public and void and throw are bold and purple, intended to stand out. Yet keywords are often the least interesting thing about a chunk of code; they are likely the thing I need to digest last. Even worthless comments stand out with the Eclipse default color scheme! At least statics are italicized; that seems OK. It’s also good that fields are colored–but unfortunately they are dark blue, which contrasts little with the other elements.

What should stand out in Java code? Fields, certainly. Where a class’s code interacts with fields is a key piece of information. As such, I configure my fields to be bright orange. For most people, the orange fields stand out like sore thumbs. Here’s the same code with my current orange-featuring color scheme:

eclipseColor

Where parameters and local variables are used is also relevant. Being able to track on a specific color for each (gold and green, respectively) can make it easier to track state changes across the body of a method (although the Eclipse feature Mark Occurrences is more useful for tracking a specific variable).

The return keyword isn’t typically very interesting, unless it occurs somewhere other than at the end of a method. No one uses underlining any more, but I’ve found that doing so can help me more quickly spot an early return.

The use of inherited fields–an odd practice, questionable at best (and one that this code doesn’t feature)–really stands out and annoys me, because I’ve made them bright red.

Emphasizing important elements is valuable, but so is de-emphasizing less relevant elements. Comments, too often not to be trusted, are now a light gray, barely visible. On days where I’m particularly affronted with the worthlessness of comments, I make them white.

While my color choices (which I change from time to time) suit me just fine, they might not suit you, however. You and I will disagree on precisely what the “right” things are to emphasize or de-emphasize. That’s ok. The key thing is to make a conscious, informed choice, and to pay attention over time to what the colors tell you about your code.

The world is full of color. Bring your IDE into that world.


Previous Compulsive Coder blog entry: The Stub Comment
Next Compulsive Coder blog entry: Typing Isn’t the Bottleneck

You can find my current color preferences for Eclipse here. You can merge these entries into the file ./.metadata/.plugins/org.eclipse.core.runtime/.settings/org.eclipse.jdt.ui.prefs in your workspace.

The Compulsive Coder, Episode 1: The Stub Comment

Some things keep coming back, such as facial hair, indigestion, and platform shoes. And for me, Java. I’m once again back in the Java world for a current engagement, and accordingly I’m again working with Eclipse.

The instant I began pairing with folks on Eclipse, my “Felix sense” kicked in, and I became unbearably indignant about the horrible defaults that too many developers simply accept. No one could tolerate more than one Ungar-ism at a time, so in this post I’ll focus on a real simple one:

public Holding findBy(String key) {
   // TODO Auto-generated method stub
   return null;
}
422769556_4094cecb03_m
Image courtesy Adam Engelhart; license

My immediate reaction was probably much like this.

A stub comment! Egads! Why in the world would people pollute their code with stub comments? Coders use their powerful IDE to auto-generate a new, empty method, but then have to waste time picking up and deleting these ugly, useless little stub comments. And horror of horrors, sometimes they don’t–I just saw a screencast where the programmer didn’t even flinch as he created and abandoned a stub comment!

The reason? Maybe it’s the 45-second effort Eclipse requires to turn off these wonderfully useless “auto-generated method stubs.” Or the painfully inadequate system for saving and restoring preferences like this (they’re all over the place), a consideration that crops up whenever you create a new workspace.

Well, I don’t want you to be able to say “I didn’t learn anything from Jeff’s blog.” Let’s start incrementing some Compulsive Coder Principles and Techniques.

Compulsive Code Principle #1
A laziness mentality is acceptable as long as you really do minimize as much work as possible. Creating stubs that need to be deleted isn’t maximally lazy.
Compulsive Coder Technique #1
Open the Eclipse Preferences dialog. Select Java->Code Style->Code Templates. (You can find it quickly by typing code templates and pressing Enter). In the right-hand side of the dialog, select Code->Method body. Click the Edit… button. Change the template’s pattern from:

// ${todo} Auto-generated method stub
${body_statement}

to:

${body_statement}

Click the OK button.

An alternative choice: Change the template to:

throw new UnsupportedOperationException("not yet implemented");

It’s an uglier version of a stub! … but, it’s so ugly it forces you to get rid of it. Where it can be helpful is in keeping you to the red-green-refactor cycle of TDD–the thrown exception will most certainly result in a failing test.

Whichever route you choose, similarly change the Code Template for Constructor body and Catch block body.

I bet you won’t ever miss the auto-generated method stubs!

Stay tuned for more Ungarisms.


Next Compulsive Coder blog entry: Syntax Coloring

Roaming Keymap Profiles

When pairing, I often learn little shortcuts and tips that I might never pick up otherwise (even though I’m the compulsive sort who comprehensively reads things like the entire list of commands, just to find some new trick). I try to impart at least as many tips as I take on. Pairing makes it happen, as there’s little better than to have an insistent partner who keeps reminding you to “just hit Ctrl-Alt-v” (introduce variable in IDEA, an essential refactoring). In the absence of a pair, IDEA’s Key Promoter plugin helps a bit.

As someone who pairs across many teams, I regularly encounter different IDEs and programmer editors. Usually teams standardize on one tool, but not long ago I worked in a C++ team where there were 8, count ’em, 8 different editors in play. Currently I am working with a team where some people are piloting Eclipse, while the rest of the team uses IDEA.

Give me a few minutes and I can ramp up OK, but switching IDEs throughout the day will make just about anyone feel stupid. Ctrl-d, duplicate line in IDEA. Switch to Eclipse, oops, Ctrl-d, I just deleted a line. Nope, it’s Alt-Ctrl-Down to duplicate a line. Move a line up, Ctrl-Shift-Up in IDEA. Wait, though, I can’t remember the Eclipse corollary, but I do have muscle memory, and so I now have to go try it… wait for me… it’s Alt-Up. And so on.

Why don’t I just change the keymaps so that they’re more in synch with each other? Or why not use, say, a vi keymap everywhere? The problem is that I’m pairing with others, and so the simplest thing is to go along with the IDE defaults (which is what the predominance of programmers uses).

On my wish list and/or backlog of things to work on, I’d love it if IDEs would support a standardized roaming keymap protocol, as well as a simple mechanism for toggling profiles. I would be able to specify a URL from which the IDE would download my profile. From there on, a simple keystroke would toggle from the active keymap profile to mine and vice versa, in order to expedite pairing.

I’ve been hoping to see more support in IDEs for things like TDD and pairing. It’s coming, albeit slowly. Any plugin fanatics out there who want to give this one a go?

NetBeans

I was very excited to start using Infinitest once again. But as things seem to go with me, I ended up moving on to something else that dominated my mindshare–in this case, a new project where I am using NetBeans. Why NetBeans? Because someone set up the project to use Maven, and all I’ve heard is that NetBeans is magical when it comes to integrating with Maven (and Eclipse, not so much).

As I would expect, both Maven and Maven support in NetBeans are really nice as long as they’re working well. But Maven seems to adhere to the 80/20 rule. It’s great 80% of the time, up until you have to do something a little out of the ordinary, or when things aren’t working like they’re supposed to. Then the numbers reverse–you spend 80% of your time trying to work on the remaining 20%. In the case of Maven, I’m struggling with getting coverage reports against multiple modules, and it’s also presenting me with a defect (operator error?) where NetBeans reports half the Maven modules as “badly formed Maven projects.” Google searches, and assistance from others with more Maven experience than me, have not been very fruitful.

This is the third time I’ve used Maven, and I’m warming up to it more each time, but it’s still been a frustration. Part of frustration is always lack of knowledge, particularly around the behind-the-scenes workings that you need to know when you hit the 20% esoterica. Thanks to those who have helped!

On the other hand, this is also the third time I’ve used NetBeans heavily. I’m not really warming to it much. Granted, part of my disappointment with NetBeans is the same problem. The best way to learn not to hate something is to pair with someone who knows it well, and I’ve not been able to get much pairing time.

Other than the Maven support, NetBeans seems much weaker than Eclipse. It’s slower (e.g. a Ctrl-O to search for types takes many seconds to return class names, compared to Eclipse’s Ctrl-Shift-t which is almost immediate). It’s flakier (e.g. half the time, ctrl-F6 to run a test pops up its JUnit GUI, the other half the time I see only the console output; also, the formatting mechanism appears to be broken). It seems to be the last of the three main Java IDEs for which people write plugins (e.g. Infinitest is only available for Eclipse and IDEA, not NetBeans). And it’s just missing key important things (e.g. there is no inline method refactoring until NetBeans 7.0).

I can live without every last bell and whistle. But it’s always disappointing to see other people whistle in cool little ways, like Kerievsky’s nice trick with inline method, and not get to play along.

Comments:

There is no way to read the Kerievsky trick without becoming a member of the Yahoo group. It would be helpful to cut and paste the content.
# posted by Anonymous Anonymous : 5/08/2010 12:59:00 AM
Aug 5, 2009, from Joshua K:

One of the refactoring strategies I defined and use quite a bit is called Parallel Change. You put new behavior next to old behavior (wherever it is) and then do a Gradual Cutover from old to new. When you’re done cutting
over to the new code, you need to get rid of the old code.

Say you’ve got some old method that was called in 10 places in a class. The new code, which had been placed under each of the 10 calls to the old code, is now doing the real work. You don’t need the old method and the calls to it.

In the past, I would delete the method, then follow the chain of red marks to delete each call to the old method. That was before a smart student pointed out a better way:

* Delete the body of the old method
* Inline the old method – effectively inlining “nothing”

That approach is much faster and far more satisfying.

Is this something folks already do? It had not occurred to me to use inline in that way to delete code.

This does go along with an observation I’ve made that the better you get at refactoring, the more you use the Inline Method refactoring.
posted by Blogger Jeff L. : 5/10/2010 07:44:00 AM

Infinitest

I recently re-downloaded Ben Rady’s Infinitest, having finally gotten back into some extended Java development work. Infinitest runs tests continually, so that you need not remember to proactively run them.

The last time I played with Infinitest, perhaps over two years ago, there was no Eclipse plugin. As I recall, on save, tests would run in a separate JUnit window external to Eclipse.

At the time, I had had a brief chance to sit with Ben and look at some of the code while at Agile 2007. I thought Inifinitest was a cool idea. But I didn’t use it extensively, partly because I’d begun to move into lots of C++ work, but also because I had a hard time fitting it into my very ingrained test-code-refactor cycle habits. Having to deal with an external window seemed disruptive.

Infinitest today is another matter entirely. Plugins have been developed for Eclipse and IntelliJ. In Eclipse, tests run as soon as you save. But they don’t run in the JUnit view–instead, test failures are reported in the Problems window, just like compilation errors. Immediately, this means that Infinitest is not disruptive, but is instead built into the normal flow of development.

Showing test failures on save is an extremely important transition, one that will help change the outlook on what TDD means. No longer are tests only an optional afterthought, something that a developer might or might not remember to or choose to run. With Infinitest, you don’t think at all about running the tests, they just run themselves. Tests are continual gating criteria for the system: If the code doesn’t pass all of its tests, Eclipse continues to point out the problem. This forces the proper mentality for the TDDer: The system is not complete unless the tests pass.

Infinitest uses a dependency tree to determine which tests must be run on save. The nice part for a die-hard TDDer like me is that my tests–my saves–will execute very quickly. This is because the die-hard TDDer knows how to design systems so that the unit tests run fast. I do wonder, however, about what this feels like for the developer on a system with lots of poor dependencies and slow-running tests. I’ll have to experiment and see how that feels.

I hate to dredge up an annoying buzzphrase, but Infinitest is really a no-brainer. I’ve only used it regularly for a few days now, but I can’t see doing TDD in Java without it.

Eclipse Auto Insert

In Eclipse, I use Ctrl-1 and Ctrl-Space so much that the wear on those three keys is noticeably more than the others.

By default, adding a new (JUnit 4 style) test is a matter of typing “test,” then hitting ctrl-space to bring up the appropriate code template. Problem is, Eclipse brings up a number of choices, and hitting enter requires ensuring the right thing is selected (it’s not always in first position) and then pressing enter. I’ve lived with this so far and didn’t think much about it until last night, when I created over 50 tests in a 90-minute session, and really resented the overhead.

I edited the template and figured checking the “Auto Insert” box would solve the problem. No dice–Eclipse presents other choices when I type “test,” such as one that just inserts the lone @Test annotation. What if I rename the “test” code template to a unique name, like “tst?” No, I get a list with two things–my template, and an option to create a method stub whose name is “tst.” No auto insert! I tried a couple other things, such as introducing a special character so that Eclipse would think it couldn’t possibly create a method with that name. That didn’t work (I don’t recall specifically what happened).

I know auto insert works in Eclipse, because I can go into the body of a method, type “sysout” and then press Ctrl-space, and Eclipse auto-completes to “System.out.println()” immediately. It requires no selection on my part. This tells me that auto insert works only if there’s one and only one possible selection. Unfortunately, it looks like that will never be the case outside a method but within the class (i.e. where one can create a “Java type member”)–any template name could also represent the name for a new method stub.

Keystrokes, then, what about assigning keystrokes? Aha. In the General->Keys preference page, I filtered for “content assist.” The choice named simply Content Assist is the one triggered by Ctrl-Space, but another choice is Content Assist (type: Template Proposals), by default assigned no keyboard shortcut. I assigned Ctrl-\ to content assist for template proposals. Now I just type “test” Ctrl-\ and I have my test method stub.

I didn’t really want another key combination, mostly because I prefer to go by IDE defaults. My pairing sessions run me through a wide variety of development environments (at last count, within the past year or so, 10 different C++ editors and 3 different Java IDEs), so it’s easiest to not create dependencies on my own personal reworking of the key mappings.

Ah well, I suppose there are a few key mappings I’ll just have to remember to configure. This is the second one I will want universally for Eclipse; the other is Rerun JUnit Test.

My wish for Eclipse is improved pairing support. The simple idea: you make your key mappings available via a URI. The first time you pair with someone, you add this to Eclipse. From there, a universally defined keystroke allows you toggle through or select from the keymaps.
Comments:

Type the template you would like to use and hit ctrl+space twice. Eclipse will bring the list with choices filtered down to templates.

Auto insert works if the template you typed is the only choice possible. That may work if you delete the old style “test” template. However it still requires you to press ctrl+space twice.

Thanks Igor. I wasn’t aware of the ctrl-space double-press. You still have to hit enter! So, it’s ctrl-space-space-enter. I would have thought this wouldn’t be required since it’s configured as auto-insert. The double-key-press would be ok, but requiring a third sucks. I like my solution better except that it’s not default behavior.

That’s why I used to live with it 😀

I don’t so much love it, but I’ve changed the the templates so that the one I want (JUnit 4 in my case) is “tst“.

Works. 🙂
MB

Right, that was my first thought, and I’m just bugged by the need to look at an unnecessary popup.

You’re right, bugs me too. Would love the “syso” behavior. I’ve been messing around with Eclipse plugins recently, maybe I’ll dig around a bit.

Cheers, MB

Atom