Saturday, April 29, 2017

Scala Dessign Patterns: Duck Typing


If it looks like a duck, swims like a duck and quack like a duck then it is probably a duck.

It is not the type of object matters but the operations that the objects supports. We can use duck typing for requiring even more methods to be available for an object by just expanding the parameter signature.

Caution: Overusing duck typing can negatively affect the code quality and application performance



Duck Typing using Scala


class SentenceParserSplit {

  def parse(sentence: String): Array[String] = sentence.split("\\s+")

class SentenceParserTokenize {

  def parse(sentence: String): Array[String] = {
    val tokenizer = new StringTokenizer(sentence)
      val hasMore = tokenizer.hasMoreTokens
      if(hasMore) {
        (hasMore, tokenizer.nextToken())
      } else {
        (hasMore, null)

object WithDuckTyping {

  def printSentenceParser(sentence: String,
                          parser: {def parse(sentence: String): Array[String]}) = {

  def main(args: Array[String]): Unit = {
    val tokenizerParser = new SentenceParserTokenize
    val splitParser = new SentenceParserSplit

    val sentence = "This is the sentence we will be splitting"

    println("Using the tokenizer parser ... ")
    printSentenceParser(sentence, tokenizerParser)

    println("Using the split parser ... ")
    printSentenceParser(sentence, splitParser)

Download Code from Github Repo



No comments:

Post a Comment