The 'anything goes' SecurityManager

As previously mentioned, my current 20% project involves some RMI hackery. Today I ran into an unfortunate error message: java.lang.ClassNotFoundException: com.publicobject.m2x.Measurer (no security manager: RMI class loader disabled) at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:371) at sun.rmi.server.LoaderHandler.loadClass(LoaderHandler.java:…

Java RMI without a webserver

One of the four steps to setup Java RMI is "Making classes network accessible." Since I'm new to Java RMI, I found this requirement surprising. We have a client and a server. Of the two of them, surely one of the two has a full set of classes.…

MiniHttpServer.java - an HTTP Server in 168 lines

For part of an project which I'll be announcing shortly, I needed an extremely lightweight HTTP server. Fortunately, HTTP is quite easy-to-implement. Tonight I hacked together MiniHttpServer.java, a simple server with zero third-party dependencies. I was able to support the core of HTTP in with just 168 lines by…

Java Minutiae - Instantiating inner classes

Pop quiz - without reflection, access to private members, or changing the source, create an instance of Inner. public final class Outer { public static final Outer INSTANCE = new Outer(); private Outer() { } public class Inner { } } Note that Inner is non-static, so each Inner has a reference to its containing Outer. Show…

Java Minutiae - Map.remove()

Suppose you'd like to remove an entry from a Map, and perform some action only if the remove actually removed. Since Map.remove() returns the value associated with the removed key, we can do this: if (map.remove(key) != null) { deleteAssociatedFiles(key); }`</pre> Unfortunately, if the map tolerates…

Java Minutiae - I love ternary

I love the ? : ternary operator. It makes my code feel tighter. Plus, I get to save code - fewer assignments, fewer return statements, and variable declarations are inline. In the code I was writing yesterday, a duplicated call to 'add()' made me itch for the ternary: for (String key…

Guice wins Jolt Award!

From the Guice User's group, Congratulations Bob, Kevin and the rest of the Guice team! Guice beat out rival Spring and several other worthy projects to win the 2008 Jolt Award for libraries and tools. It was great to see the guys win - they deserve to be recognized for…

Java Minutiae - @return

Often I see Javadoc with only an @return tag: /** * @return the current user assigned to make the delivery, or {@code null} * if no such assignment has been made. */ public User getDeliveryPerson();`</pre> Unfortunately, the `javadoc` command line tool doesn't handle this format particularly well. Since the method has…

Guice commands

I recently checked in a new Guice extension called commands. The goal is simple - make it possible to modify your modules at runtime. But modules aren't naturally data, they're more like code: Module module = new AbstractModule() { protected void configure() { bind(Soda.class).to(Coke.class); bind(Snack.class).to(…

Java Minutiae - Class.toString()

Class.toString() doesn't return what you'd expect: assertEquals("java.lang.Integer", Integer.class.toString());`</pre> Instead, it prefixes the fully-qualified classname with "class " for classes, "interface " for interfaces and probably "enum " and "annotation " elsewhere. You need to call…

Java.net Poll on Closures

Java.net is having a poll on which version of closures is preferred for Java 7. I think this is a great opportunity for First-Class Methods (FCM) to get some attention as a worthy contender. Closures offer us the opportunity to make our Java code simpler by making the Java…

Java Minutiae - Array class literals

Guice loves class literals: bind(Foo.class) .toProvider(FooProvider.class);`</pre> Today I found out that there's a simple syntax for declaring a literal array. Just add an extra pair of square brackets: <pre class="prettyprint">` bind(Foo[].class) .toProvider(FooArrayProvider.class);…

Java Minutiae - Arrays.hashCode()

I'm working on a simple API that deals with raw arrays - yuck! Did ya know that Arrays.hashCode(a) is the same as Arrays.asList(a).hashCode()? Somebody smart made it easy to migrate from arrays to Lists.…

Anal Retentive Java Style - Annotation Placement

A shared codebase means a shared styleguide. An issue that's come up a lot recently is where to put the damn @Override tag, and similar marker annotations. Above: @Override public String toString() { return "Delivery " + id; }`</pre> ### Inline <pre class="prettyprint">` @Override public…

Be Minty #2: Aggressively enforce constraints

Part 2 in a series. Suppose we have a simple interface that can initiate a delivery: interface DeliveryService { /** * Schedules {@link order} for immediate delivery to {@link destination}. * * @return a snapshot of the delivery in progress. */ Delivery scheduleDelivery(Order order, Address destination); ... }`</pre> Naturally there are several possible implementations…

Be Minty #1: returning Collections

In this series I document patterns, techniques and styles for designing fantastic APIs in Java. My target audience is software developers working with big teams on big projects. Many of the suggestions should be overkill for a weekend project. Topics in this series will range from simple style issues to…

Use the Google Chart API

Want sexy charts, but without the grief of Excel? In your blogs, emails, and projects? Use the recently released Google Chart API for fast and easy charts. Google Chart API Let's suppose we want to make the above pie chart. We simply build a URL that describes the image, and…

Who holds the remote control?

I have a DVR built into the receiver for my Canadian satellite dish. It's fantastic. I love being able to record Canadian football games and to do my own instant-replays when I see something great. Tonight I'm home alone - Jodie's out shopping in San Francisco. When I got home,…

Don't do this: evading polymorphism

I've got two classes, Base and Sub. I can freely make changes to Base. But Sub is written by a third party and I don't have privileges to make changes to it. Here's what they look like: public class Base { public void prepareForMission() { loadUpInfantry(); loadUpWeapons(); } } public class Sub extends Base…

CorelDraw on Mac discussion forums

Long before I was writing code, I liked to play with the CorelDRAW graphics suite. Unfortunately, Corel abandoned the Mac market five years ago! I've blogged some tips and tricks on getting CorelDRAW to run on new Macs. And a lot of people searched for them on Google and commented…

Stephan Schmidt on type inference

Stephan Schmidt writes, Beside the fact that my IDE does the typing with auto completion - of course the compiler knows - DUH. But the developer does not know.I couldn't agree more with his recent post on programming languages.…

Simpler service interfaces with Guice

I'm using Guice throughout my code, and I've found a pattern that works rather nicely. Suppose I've got a service interface method for scheduling a delivery: public interface DeliveryService { /** * Schedules {@link order} for delivery and returns a snapshot with * the details of the scheduled delivery. * * @param loggedInUser the customer service…

Java 6 and Mac OS X 10.5

I'm fairly confident that Apple will be posting a download of Java 6 shortly. One of the MRJ developers gave a talk at Desktop Matters, and Java 6 is definitely being worked on. But I feel compelled to dispute a recent post on John Gruber's blog: Apple’s decision to…

Implementing equals() is hard

When modeling an entity that may or may-not have an id assigned, writing the equals method is surprisingly hard. What to do when there's no id? Falling back on equals-by-value is tempting: public class Product { private final Id id; private final String description; private final Money price; ... public boolean equals(…

A simple pattern for avoiding NullPointerExceptions

Imagine you've got some method that sometimes returns a legitimate value, and other times returns the special value null to indicate that no legitimate value exists: public interface StoreLocator { /** * Returns a store nearest to {@code address}, or {@code null} * if there are no stores within delivery range of the address.…

My favourite bookmarklets

A bookmarklet is a tiny JavaScript program that lives inside a link. Drag each of these to your browser's bookmark bar - they add simple features to every page you visit: ← go to the "previous" page. This works for pages with numbers in the URLs, like Engadget or…

Catching unchecked exceptions is fragile

In my project we're having a great discussion about whether to use checked or unchecked exceptions for a particular problem. I've discovered an interesting problem with unchecked exceptions - they're not as robust with respect to refactoring and maintenance. Here's some code that gracefully handles the unchecked exception called MappingServiceUnreachableException:…

Ten blogs for your feedreader

I'm a big fan of blog feeds. As a blog author, they give me an audience to whom I can blast my ideas. And as a blog reader, I can grab the latest content from 159 blogs in just a few seconds. If you're still surfing the web by hand,…

Don't let consistency rule your APIs

Consistency in API design is great. It makes the API more predictable, easier to learn, and more maintainable. But I believe there's a difference between being consistent when writing code, and writing code to be consistent. Consider this API: public enum Status { PENDING, PREPARATION_IN_PROGRESS, PREPARED, DELIVERY_IN_PROGRESS,…

Don't fly AirTran

AirTran sold my seat out from under me today for my trip from Buffalo to San Francisco... I made my annual trip back to southwestern Ontario this weekend to attend Oktoberfest in Kitchener, and to see the 'Riders. Jodie and I flew through Buffalo airport to save some bucks -…

Airport WiFi thinks my newsreader is a virus

This morning while waiting for a connection at the Atlanta airport, I signed up for $7.95/day WiFi. It's a lot of cash for Internet, but I'm a news junkie and I wanted to sync up on work email, etc. As usual, when I got online I refreshed all…

Spammy Java

Compare these two code snippets, they both do the same thing. Minimalist public static <T> Comparator<T> reverse(final Comparator<T> forward) { Preconditions.checkNotNull(forward, "forward"); return new Comparator<T>() { public int compare(T a, T b) { return forward.compare(…

Considering Guice: Explicit dependencies

I love Guice. So much so that lately I've been trying to push it on my friends for their projects. But my friends are reluctant. They've become accustomed to manually solving the problems that Guice could solve for them. They enjoy wiring up their apps and implementing singletons, factories and…

Be conservative in what you accept and conservative in what you send

It's tempting to write overly-friendly APIs: public void setDeliveries(List<Delivery> deliveries) { if (deliveries == null) { deliveries = Collections.emptyList(); } this.deliveries = Collections.unmodifiableList( new ArrayList<Delivery>(deliveries)); } Please don't do this: It masks bugs. The caller might be passing the wrong deliveries object, such as orderDeliveries when…

Bean-independent Properties

I just posted the first draft of a proposal for Bean-independent Properties for the Java language. This started when I was CC'd on email from Mikael Grev who prefers bean-attached properties. I prefer the opposite, so I figured I'd make my preference concrete. This is quite similar to an implementation…

JSRs aren't appropriate for classlibraries

In addition to more platformey changes and language changes, the JCP develops standard classlibraries for the JDK. Let's contrast this process to open source development of classlibraries. In particular I'm thinking about libraries like binding, app frameworks, units/measures, date/time, module systems, and object-relational mapping. Code Quality JCP: consistently…

Series Recap: Coding in the small with Google Collections

Robert Konigsberg, Jerome Mourits and myself have written several snippets that highlight the carefully designed Google Collections Library: Preconditions Preconditions.checkNotNull(order.getAddress(), "order address");`</pre> [Iterables.getOnlyElement](/2007/09/coding-in-small-with-google-collections_9985.html)<pre class="prettyprint">`assertEquals(jesse, Iterables.getOnlyElement(usersOnDuty));`<…

Coding in the small with Google Collections: ClassToInstanceMap

Part 14 in a Series. ClassToInstanceMap is a specialized Map whose keys are class literals like PizzaPromotion.class or RestockingInformation.class and whose values are instances of those types. It provides a convenient balance between type safety and model flexibility. In some code I wrote recently, I needed to attach…

Coding in the small with Google Collections: BiMap

Part 13 in a Series by Jerome Mourits, Guest blogger... A BiMap is a map that supports an inverse view. If you need to map from key to value and also from value to key, then a BiMap is what you want! Note that the values of a BiMap must…

Coding in the small with Google Collections: Comparators.fromFunction

Part 12 in a Series. Comparators.fromFunction() allows you to create a Comparator based on the properties and attributes of a your business objects. Since the same function is applied to both of the values to compare, this method makes it easier to write a symmetric comparator: Before: public Comparator&…

Coding in the small with Google Collections: Maps, Sets and Lists

Part 11 in a Series by Jerome Mourits, Guest blogger... Generics are good, but they can be really wordy! Before: Map&lt;CustomerId, BillingOrderHistory&gt; customerOrderHistoryMap = new HashMap&lt;CustomerId, BillingOrderHistory&gt;();`</pre> ### After: <pre class="prettyprint">`Map&lt;…

Coding in the small with Google Collections: Join

Part 10 in a Series by Jerome Mourits, Guest blogger... Join makes it easy to join Strings separated by a delimiter. Before: public class ShoppingList { private List&lt;Item&gt; items = ...; ... public String toString() { StringBuilder stringBuilder = new StringBuilder(); for (Iterator&lt;Item&gt; s = items.iterator(…

Coding in the small with Google Collections: Multimap

Part 9 in a Series by Robert Konigsberg, Guest blogger... Multimap is like a Map, but lets you store multiple values for every key. It turns out this is frequently useful. Consider how often you have had to create, for instance, a Map<K, List<V>>…

Joel forecasts the SDK of the future...

Joel Spolsky is generally a great writer, but he didn't do his research for today's post. He claims that with the web, JavaScript is the new assembly language: it's capable but not portable: [...] build a programming language, like C, that’s portable and efficient. It should compile down to “native”…

Coding in the small with Google Collections: Constraints.constrainedList

Part 8 in a Series. Constraints.constrainedList allows you to enforce rules about what can be added to a List instance. By letting the List manage its constraints, your API users get instant feedback if they insert invalid values. It also allows you to expose convenient methods like addAll() and…

Coding in the small with Google Collections: Iterables.concat()

Part 7 in a Series. Iterables.concat() combines multiple iterables (such as ArrayList and HashSet) so you can go through multiple collections' elements in a single pass: Before: public boolean orderContains(Product product) { List&lt;LineItem&gt; allLineItems = new ArrayList&lt;LineItem&gt;(); allLineItems.addAll(getPurchasedItems(…

Coding in the small with Google Collections: Objects.nonNull

Part 6 in a Series by Robert Konigsberg, Guest blogger... In the first episode, Jesse talked about the Preconditions class. That's not the only mechanism supplied by the Google Collections library for data validation. We're going to look at Objects.nonNull(T) and, by association, Objects.nonNull(T, String). Objects.…

Coding in the small with Google Collections: ImmutableList.copyOf

Part 5 in a Series. ImmutableList.copyOf() creates an immutable copy of it's arguments as a List. Wherever your code stores a List parameter, it may need an immutable copy. With the JDK, coping and preventing modification requires two steps. Lists.immutableList simplifies this code: Before: public Directions(Address from,…

Coding in the small with Google Collections: Objects.equal and hashCode

Part 4 in a Series. Objects.equal(Object,Object) and Objects.hashCode(Object...) provide built-in null-handling, which makes implementing your own equals() and hashCode() methods easy. Before: public boolean equals(Object o) { if (o instanceof Order) { Order that = (Order)o; return (address != null ? address.equals(that.address) : that.address == null)…

Coding in the small with Google Collections: Comparators.max

Part 3 in a Series. Comparators.max takes two Comparables and returns the larger of the two. It improves upon the standard approach, which requires both a comparison and a ternary: Before: public Money calculateDeliveryCharge(Order order) { double distanceInKm = Geography.getDistance( storeAddress, order.getAddress()); Money perKm = pricePerKm.times(distanceInKm); _return…