Tuesday, September 1, 2009

Refactoring if to match

One of the refactorings I find myself doing quite often in Scala is converting large branching if trees into an easy to read match statement. The reasoning is that it is much easier to read a match statement because it is like reading bullet points rather than trying to follow the flow of information through a tree of if statements.

Before you complain, I realize there are other ways to refactor a tree of if-statements but I find the match statements the easiest to reason about and the quickest to write with the least amount of boiler plate.

Here is an example where I need to see if the file is dirty and needs to be regenerated, if it is clean or if some one has modified the generated file (which results in a CONFLICT).

  1. object State extends Enumeration {
  2.   final val DIRTY, CLEAN, CONFLICT = Value
  3. }
  4. if( !pom.file.exists ){
  5.   DIRTY;
  6. }elseif (checksum.file.exists) {
  7.   val sha = new String(MessageDigest.getInstance("SHA").digest( pom.slurp.getBytes ))
  8.   if( sha == checksum.slurp ) CLEAN
  9.   else DIRTY
  10. } else {
  11.   CONFLICT
  12. }
  13. pomFile(massFile) match {
  14.   case (pom, checksum) if (!pom.file.exists) => DIRTY
  15.   case (pom, checksum) if (!checksum.file.exists) => CONFLICT
  16.   case (pom, checksum) => {
  17.     val sha = new String(MessageDigest.getInstance("SHA").digest( pom.slurp.getBytes ))
  18.     if( sha == checksum.slurp ) CLEAN
  19.     else DIRTY
  20.   }
  21. }

No comments:

Post a Comment