- Shorter Programs, But Not the Way You Think
- Extreme Decoupling
- Required Ceremony Versus Programmer-Driven Clarity
- Staying Out of Trouble
- In the Wild
- Wrapping Up
Required Ceremony Versus Programmer-Driven Clarity
One thing that variable declarations do add to code is a modicum of documentation. Take the initialize method of our Document class:
def initialize( title, author, content )
Considerations of code flexibility and compactness aside, there is simply no arguing with the fact that a few type declarations:
# Pseudo-Ruby! Don't try this at home! def initialize( String title, String author, String content )
Would make it easier to figure out how to create a Document instance. The flip side of this argument is that not all methods benefit—in a documentation sense—from type declarations. Take this hypothetical Document method:
def is_longer_than?( n ) @content.length > n end
Even without type declarations, most coders would have no trouble deducing that is_longer_than? takes a number and returns a boolean. Unfortunately, when type declarations are required, you need put them in your code whether they make your code more readable or not—that's why they call it required. Required type declarations inevitably become a ceremonial part of your code, motions you need to go through just to get your program to work. In contrast, making up for the lost documentation value of declarations in Ruby is easy: You write code that is painfully, blazingly obvious. Start by using nice, full words for class, variable, and method names:
def is_longer_than?( number_of_characters ) @content.length > number_of_characters end
If that doesn't help, you can go all the way and throw in some comments:
# Given a number, which needs to be an instance of Numeric, # return true if the number of characters in the document # exceeds the number. def is_longer_than?( number_of_characters ) @content.length > number_of_characters end
With dynamic typing, it's the programmer who gets to pick the right level of documentation, not the rules of the language. If you are writing simple, obvious code, you can be very minimalistic. Alternatively, if you are building something complex, you can be more elaborate. Dynamic typing allows you to document your code to exactly the level you think is best. It's your job to do the thinking.