In my other series of posts about ScalaMUD, I’ve been writing a lot of code – some of it good, some of it ugly as hell. The reason a lot of the code looks ugly is that, as a C#, Java, and Objective-C developer my gut instinct is to do things in an imperative style with if statements, for loops, and other such constructs that simply don’t look at home in a hybrid functional language like Scala.

Here’s the code I originally produced, which scans through a list of NLP-tagged words and retrieves the first verb. If the list is empty then we need to return an empty string and if the list has no verbs then we assume that the first (or only) word in the list is a verb. For example, if I type “who” or “uptime” into the game then these should be considered verbs for command dispatching, even though NLP says they’re not verbs per se.

Ugly as Sin Code:

def firstVerb = {
if (words.size == 1)
words.head.value
else {
val outWords = words.filter( word => word.pos == Verb)
if (outWords == Set.empty)
words.head.value
else
outWords.head.value
}
}

And thanks to the geniuses over at Stack Overflow, they were able to guide me to this incredibly simple, elegant refactoring:

Refactored Code:

words find(_.pos == Verb) orElse words.headOption map(_.value) getOrElse ""

My hope is that someday I will think in terms of the second, more clean and refactored version and not instinctively reach for my imperative crutches.