Dynamic Type Check

2 June 2009

Recently some of our developers ran into the accusation that with a dynamic language like ruby you use so many dynamic type checks that you end up effectively writing your own type system. So they thought, since we've written a lot of real ruby code - how often do we make dynamic type checks? Michael Schubert gathered up the data.

The table below contains the data. We define a dynamic type check as the use of the methods is_a?, kind_of?, and instance_of?. The lines of code come from the standard rake stats command in rails.

Project IDCode type checksCode LOCTest type checksTest LOCLOC / type checktest LOC / code LOC
A16133180985614480.7
B141913801712325900.9
C02607029811.1
D74265340698331.0
E3229619609768813843.3
F18~9500N/AN/A528N/A
G02455032901.3
H92220664045752.9
I23106332123319191.2
J1964046124885115862.2
K175769698486791.7

The moral of this data is that you shouldn't expect to see a lot of type check calls in your ruby code base. This, of course, is true of any dynamic language. It was generally considered bad form in Smalltalk circles I inhabited too.

The methods that were checked for in this data aren't the only ones that can be considered a dynamic type check. Other cases are respond_to? and aClass === anInstance. Our folks felt that these cases were no more common than the ones they checked for.

Most uses are those of dealing with liberal input - eg where a method parameter can be a string, symbol, or array. These crop up in DSLish situations where you want liberal input for the high readability.