Type safety is a means, not an end

Java's type system isn't expressive enough to model everything exactly. But it's expressive enough to be productive!

Our type-unsafety-is-okay precedent is Collection.clear(), JJB's infamous optional method. Type safety advocates see @throws UnsupportedOperationException and claim that it's damning of either the collections framework or the type system. But I claim that each new type (or type parameter!) has a complexity cost and that it may occasionally be better to have fewer types than a perfectly typesafe API.

The tricky bit is deciding where to draw the line. Dynamic language folks ("liberals") think that type safety is overpriced and will prefer fewer types and more possibility for runtime errors. Type safety junkies ("conservatives") want to model the universe as it truly is and must accept a world with type variables, covariance, and wildcards.

What isn't productive is going against the grain of the type system. If you find yourself copying & pasting class declarations to work around a language limitation, you may be trying to use more type safety than the language will bear. Type safety can be unintrusive like a seatbelt. But using APIs with more than two type parameters feels like driving to work in Lancelot's armor.

The opposite end of the spectrum is also quite terrible. An old billing system I worked on used Map<String, Object> as its preferred datatype. We'd live in fear that using an equals() where equalsIgnoreCase() was necessary would cause the next million dollar bug. To use this API was to vomit null checks and casts until simple business logic became complex.

Our jobs as software engineers is to make tasteful decisions about how much type safety is appropriate.


Ken said...

Agreed. My motto is "everything in moderation". Taking anything to an extreme whittles away it's broader value.

As I've used Objective-C and Cocoa (not at all type safe compared to Java and it's standard APIs) exclusively over the past 4 or so months, I've found myself missing the comfort of generics. But in practice, they wouldn't have caught any bugs for me in what I've written up until this point. Granted I'm not writing public APIs, but it has still given me pause to think about the value of restrictiveness. I've had to increase my usage of asserts in order to declare my expectations, so perhaps some compile time safety would be a bit better.

Again, I think balance is the name of the game.

theclippers said...

Any chance of this app for the iPhone?