Saturday, July 19, 2008

Beautiful Code: Runtime Type Checking

This post is part of the Beautiful Code series.

I have to admit, the title of this post might be misleading. Scratch that: It is misleading. This post is actually about a lack of runtime type checking. This quote is from Greg Kroah-Hartman, on a chapter about the Linux kernel driver model. He has explained some concepts, and given some code samples, and then he says this:

If you notice, there is no runtime type checking to ensure that the pointer that was originally passed as a struct device really was of the struct usb_interface type. Traditionally, most systems that do this kind of pointer manipulation also have a field in the base structure that defines the type of the pointer being manipulated, to catch sloppy programming errors. It also allows for code to be written to dynamically determine the type of the pointer and do different things with it based on its type.

The Linux kernel developers made the decision to do none of this checking or type definition. These types of checks can catch basic programming errors at the initial time of development, but allow programmers to create hacks that can have much more subtle problems later on that can’t easily be caught.

Whoa. In the Linux kernel driver model, in this instance, they don’t do runtime type checking. But what if a developer passes the wrong kind of struct? Well, if I may paraphrase Kroan-Hartman—perhaps incorrectly—if people are passing the wrong kind of struct, then they have bigger problems. Frankly, if the code did do runtime type checking, developers would probably simply set the appropriate value in the struct, until they found a value that worked. They’d still have the problem, they’d just mask it, but now it would be hard to track down and find. So why waste the kernel’s time doing this runtime type checking, when it’s not really going to buy anything anyway?

Is this a lesson that we can apply in other areas? Maybe, although you’d have to be very careful about it. We’re not all writing Linux, folks. And, to be clear, the parts of the Linux kernel being discussed in this chapter aren’t really worked on by thousands, hundreds, or even dozens of people. There are only a limited subset of people who are working on the Linux kernel driver model. That makes a difference too.

0 comments: