Before:
#Find playlist by name and add to list.
if config.has_key?('playlist')
config['playlist'].each do |name|
playlists.push(interface.LibrarySource.Playlists.ItemByName(name))
end
end
#Create playlist and add to list. [Note the near-identical code.]
if config.has_key?('create-playlist')
config['create-playlist'].each do |name|
playlists.push(interface.CreatePlaylist(name))
end
end
#...etc.
After:
#Invoke a block with each of the values for the given option in the given configuration.
def with_option_values (key, config)
if config.has_key?(key)
config[key].each do |value|
yield value
end
end
end
#Find playlist by name and add to list.
with_option_values('playlist', config) do |name|
playlists.push(interface.LibrarySource.Playlists.ItemByName(name))
end
#Create playlist and add to list.
with_option_values('create-playlist', config) do |name|
playlists.push(interface.CreatePlaylist(name))
end
…Two completely different operations, but with yield and blocks, I’m able to remove the boilerplate around them. Multiply that across a dozen similar sections of code, and you start to see real readability improvements.