プログラミング雑記

プログラミングの雑記です。

Closureを利用したリファクタリング例

import java.io.File

object Main extends App {
}
object FileMatcher {
  private def filesHere: Array[File] = new File(".").listFiles
  def filesEnding(query: String) =
    for (file <- filesHere; if file.getName.endsWith(query))
      yield file
  def filesContaining(query: String) =
    for (file <- filesHere; if file.getName.contains(query))
      yield file
  def filesRegex(query: String) =
    for (file<-filesHere; if file.getName.matches(query))
      yield file

  def filesMatching(query: String, matcher: (String, String) => Boolean) =
    for (file<-filesHere; if matcher(file.getName, query))
      yield file
}
object FileMatcherWithBoundFunction {
  private def filesHere: Array[File] = new File(".").listFiles
  def filesEnding(query: String) =
    filesMatching(query, _.endsWith(_))
  def filesContaining(query: String) =
    filesMatching(query, _.contains(_))
  def filesRegex(query: String) =
    filesMatching(query, _.matches(_))

  def filesMatching(query: String, matcher: (String, String) => Boolean) =
    for (file<-filesHere; if matcher(file.getName, query))
      yield file
}
object FileMatcherWithClosure {
  private def filesHere: Array[File] = new File(".").listFiles
  def filesEnding(query: String) =
    filesMatching(query, _.endsWith(query))
  def filesContaining(query: String) =
    filesMatching(query, _.contains(query))
  def filesRegex(query: String) =
    filesMatching(query, _.matches(query))

  def filesMatching(query: String, matcher: String => Boolean) =
    for (file<-filesHere; if matcher(file.getName))
      yield file
}