Atom Feed SITE FEED   ADD TO GOOGLE READER

Your mind is a terrible profiler

Today I found the following interface while doing a code review:
interface DeliveryListener {
void deliveryFulfilled(Delivery delivery);
void deliveriesFulfilled(Set<Delivery> deliveries);
}
This code offends me because the first interface method is a special case of the second method. Why not just use a singleton list! When prompted, the code's author claimed that providing two methods was better:
  • The JVM wouldn't have to create a whole object just to invoke a method.
  • All implementations of the 2nd method will just for through the Set and invoke the first method anyway, so it doesn't cause the implementor to have to do additional work.

    Creating a whole object is a waste of CPU
    Your mind is a terrible profiler. The deliveryFulfilled method would not be a hotspot in the application, so micro-optimizations like this one only serve to obfuscate the source code. Whenever you review code and the justification for design is "optimization", be very suspicious. Never trust any optimization that doesn't have a repeatable test that justifies its existence.

    The second method invokes the first method anyway, so the cost is zero
    If this was the case, then the calling code should just do the loop for you, and only the first method should exist. Leaking implementation details in the interface is a bad thing, because it forces the design.

    As software engineers, we're paid to express business processes in Java code. Our business models should be as simple and straightforward as possible. Leave the optimizations for later, you'll do a better job.