Archive for the ‘Code’ Category

IDE’s Slow Me Down

{Monday, November 7th, 2005}

I recently came across some experienced developers that continue to use a trusty text-editor for development purposes.

Now….I can recall the days when I considered auto-completion to be the root of ignorance – how could you possibly learn an API by not referring to its doco? Surely you’d be more encouraged to commit the API to memory without auto-completion? I could always find situations where an editor would automatically do something that wasn’t what I intended – insert spaces here, use tabs there, name variables poorly, place brackets in the wrong location. To cut to the chase, I imagined a plethora of reasons for holding back.

Sure, IDE’s had many drawbacks – 5 year ago. If you hold to these beliefs today, simply put, you’re a dinosaur. IDE’s of today allow developers to reap substantial productivity rewards. They are more configurable and more intelligent, they make class navigation and manipulation a breeze.

Still, hold a discussion with these lads about it and you’d soon delve into an emotion charged discussion, logic and reason taking a back-seat. Somehow it always rose to the top-tier of the NLP rung, like a child feverishly gripping their blankie. To them it was no sweat to ask developers using IDE’s to perform refactorings difficult to express in regular expressions. When pairing with these developers you’d quickly get a feel for how simple activities - like file navigation, refactoring, getting code to compile – were painstakingly drawn out. Clearly the implications of this attitude are more significant on Agile projects.

Much has to be said for allowing developers the freedom to choose their preferred development tools – but I guess this type of freedom implies ’so long as productivity is not compromised’.

Certainly without an IDE productivity is compromised. Please conscientious development teams, veto the use of text editors for development purposes. It should be non-negotiable, no argument could reasonably justify their use. If you continue to use them, I offer some simple advice - evolve or perish.

Exception Cause or Effect?

{Monday, May 9th, 2005}

I’ll have to relent on my previous post, exceptions is not a dead topic after all. I’ve recently encountered some mis-uses and nuances that warrant discussion. Consider the exception handling construct:

reserveResources();
try {
    performLogic();
} finally {
    releaseResources();
}

It’s a classic that is particularly common when performing JDBC operations, the resources in this case being PreparedStatements, Connections and Transactions. Granted, the catch block can play an important role, but let’s ignore that for now.

Consider this scenario; logic failure resulting in an exception, then resource release failure. What exception is propagated – logic failure or the more incidental releasing of resources? Mr.Finally will always win that battle unless you declare otherwise.
It’s staggering the amount of times I’ve seen this oversight in practice. This approach is, of course, very acceptable if the finally exception has greater importance, but that is a rare situation. Too often, especially with non-TDD approaches, developers place exception handling in the back of there mind, exception flows are usually not considered until normal flows are codified. Staggeringly, in some cases I’ve seen code realized in this order as well – code the normal stuff, then add exception handling later. Resist this urge! Exceptions can and should be considered more fundamental aspects of an objects behavior.

So what’s the best approach. Let’s see….

reserverResources();
Throwable originalException = null;
try {
    performLogic();
} catch (Throwable throwable) {
    originalException = throwable;
} finally {
    try {
        releaseResources();
    } catch (Throwable throwable) {
        if (originalException == null) {
            originalException = throwable;
        } else {
            log.error(“Exception releasing resources.”, throwable);
        }
    }
}
if (originalException != null) {
    throw originalException;
}

Or perhaps this:

reserveResources();
try {
    performLogic();
} finally {
    try {
        releaseResources();
    } catch (Throwable throwable) {
        log.error(“Exception releasing resources.”, throwable);
    }
}

In each case the logic exception is preserved. Before I explore the pro’s and con’s of each approach, lets revise some best practices:

  • Process exceptions once and only once. Processing typically involves logging and presenting a message to the user.
  • Minimize generic catch blocks, such as catch (Exception exc) or catch (Throwable throwable), reducing the probability of gobbling exceptions that would otherwise be propagated.
  • Treat exceptions consistently to facilitate maintainability, just like any cross-cutting concern. At its best consistency is achieved through centralized logic, so centralize exception handling - a simple example is web application error handling via the web.xml element declarations. I’ve seen plenty of violations of this rule, logging exceptions at multiple points – the classic violation being logging exceptions at their origin, promoting code scattering.
  • Propagate at most one checked exception (see my previous blog on this principle). The exception should have meaning in the context of the method – akin to Domain Driven Design Intention-Revealing Interface principles.

With these practices in mind let’s consider the revised approaches:
Approach One

  1. Multiple violations of minimizing generic catch blocks.
  2. Code is relatively verbose – a minor point, but a point nonetheless.
  3. The exceptions are not re-thrown from a line indicating where the exception occurred (they are now both thrown from the lower if block), so the stack trace will slightly less communicative.

Approach Two

  1. Violation of minimizing generic catch blocks.
  2. The exception in the finally block is never propagated. Clients to this code will not be aware of any resource release failures, potentially losing critical information influencing subsequent processing or presentation to the user.

The first approach certainly seems the better of the two evils, but we’ve violated the generic catch block principle in each case. Mr. Checkstyle will explode with the appropriate settings.

IllegalCatch is not legal in all circumstances.

Let’s consider this check in more detail, it minimizes the chance of inadvertent exception consumption. It’s a safeguard for silliness. It is by no means a safeguard for something there is no good reason for doing, like not declaring a class with purely static behaviour as final.
It’s more compelling to violate this principle when developing infrastructure, but it holds as a hard and fast rule for standard application logic. In light of this I’ve changed my stance on this check:
Prevent inadvertent exception consumption in application logic using Checkstyle. For infrastructure development, rely on the pair or a review to prevent inappropriate generic catch blocks. This could be better realized by limiting the applicability of this check to certain packages – unfortunately Checkstyle’s IllegalCatch check does not support this.

I’ve seen a work around to this problem (aka hack) by employing a control flag approach:

int success = 0;
try {
    doSomething();
    success = 1;
} finally {
    if (success == 0) {
        // Exception occurred
    }
}

Clearly this code is not as communicative and ventures to the days of languages void of exception constructs. Still, it’s another evil that you need to weigh into the equation determining which approach is best, but it’s an option that wouldn’t be considered if IllegalCatch was more flexible.

Excessive Exceptions

{Thursday, March 24th, 2005}

From my experience, plenty of developers are still confused about how to nicely use exceptions. I find this staggering given the mass of flame wars over the years on kosher exception use. Simply put, some people just need to be force fed - the drone community is alive and well. But, back to the big debate. When to check and when to uncheck? Given the confusion I’ve seen reign recently, it’s about time I at least started a tiny spot fire in the war.

Once upon a time I used to think this it was a clear good vs. evil battle (in that order) – no exceptions (pardon the pun). But Spring somewhat twisted my point of view. Unchecked’s are an excellent alternative for offering clients the option to handle an exception. As Spring suggests, this is especially useful in the case of fatal, unrecoverable exceptions. Remember, unchecked exceptions can be declared in throws clauses too, so clients can somewhat expect the exception by perusing the method signature. That’s something to consider, but I don’t recommend it. It is a very human process requiring too much discipline to enforce and can yield too much clutter to warrant the effort, especially in highly cohesive code with deep invocation chains, and goes against Checkstyle’s Throws Count check. As a parting word on the war of checked vs. unchecked, perhaps it draws parallels to another old war on strongly typed versus dynamic languages, with checked similar in nature to strongly typed and unchecked similar to dynamic. Some want the immediate feedback of the compiler, others consider this step more of an unnecessary burden. In the case of exceptions the burden is being forced to handle exceptions at layers that can’t do anything about it.

But the big war I’ve been fighting recently is on the number of acceptable declared exceptions per method. My preference is one per method, Checkstyle’s default. In recent times I’ve cringed at code with as much as 10 checked exceptions per method. I’m accustomed to complaining about standard JDK methods with what I consider excessive exception contracts. Reflection exceptions are a good example with one method invocation potentially causing a IllegalAccessException, IllegalArgumentException or an InvocationTargetException. I never care which exception occurred – I handle these exceptions the same way. But that’s only 3 exceptions. 10 is a completely different ball-game. The side-effects are repetitive, messy client code, confusion reigning on kosher use of the method, and nightmarish unit testing as it’s difficult to exercise all exception conditions. Indeed, this type of exception misuse has all the evils that using control flags to govern execution flow brings. As a client forced to use this code, you can pray for an alternative or write one, but that violates the Once and Only Once rule. Better is writing a proxy insulating you from the exception handling cruft. Better still is refactoring, but I find these smells emanate on the bio-hazard scale where, without a significant investment, all you are likely to achieve is scratching the surface of the code with a vein hope of someday achieving your refactoring goals.

As always, it’s best to educate and fix the problem at it’s source somewhere in the mix. So how do you argue the nuance’s of kosher exception practices with someone that doesn’t know any better? Surely key to any sound argument on this is general OO modeling best practice. Strive to create classes with very distinct responsibilities and logical methods with clear single causes of failure. Having 10 exceptions in a method is certainly possible if you’ve written an OO script thats a couple of hundred lines long. Yeah, sure it’s possible. But if that’s your way of thinking, OO is not for you and you probably should be using a language that doesn’t have the concept of an exception. Try C instead. Better still, try joining these clowns.

As an example of a nice OO approach, consider the needs of a graphics application that allows the user to draw shapes. Consider this method in the ShapeRenderer interface;

void render(Shape shape) InvalidShapeException, CircleOutOfScreenBoundsException, ShapeOutOfScreenBoundsException, IllegalShapeDimensionException, ShapeAlreadyRenderedException, UnrenderableShapeException;

vs. this method;

void render(Shape shape) throws RenderingException;

It’s blatantly obvious which one is more understandable, decoupled, and which one clients will take a liking to. A common argument I hear defending masses of exceptions is ‘I want the user to receive a different error for each exception’. Fine - there are far cleaner ways of achieving this goal. For instance centralized converter infrastructure responsible for converting failures to meaningful messages is a good example. What you use as the key to your conversion certainly does not have to be the exception class. Sure it can play a role of great importance, especially with logical exception hierarchies, but exceptions are objects that can contain any information. Use that to your advantage.

Another argument I often hear is ‘Why not just throw Exception or Throwable? That’s one exception’. Consider the side-effects; clients lose context as it communicates the method can fail for any reason and exceptions can be inadvertently gobbled. Indeed this strategy has lead to Checkstyle’s Illegal Catch check being invented.