Saturday, April 29, 2017

Scala Dessign Patterns: Duck Typing

Introduction

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

 

Agenda:

Duck Typing using Scala

 Code:


class SentenceParserSplit {

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

class SentenceParserTokenize {

  def parse(sentence: String): Array[String] = {
    val tokenizer = new StringTokenizer(sentence)
    Iterator.continually({
      val hasMore = tokenizer.hasMoreTokens
      if(hasMore) {
        (hasMore, tokenizer.nextToken())
      } else {
        (hasMore, null)
      }
    }).takeWhile(_._1).map(_._2).toArray
  }
}

object WithDuckTyping {

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

  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

 

References:

No comments:

Post a Comment