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).
- object State extends Enumeration {
-   final val DIRTY, CLEAN, CONFLICT = Value
- }
- if( !pom.file.exists ){
-   DIRTY;
- }else if (checksum.file.exists) {
-   val sha = new String(MessageDigest.getInstance("SHA").digest( pom.slurp.getBytes ))
-   if( sha == checksum.slurp ) CLEAN
-   else DIRTY
- } else {
-   CONFLICT
- }
- pomFile(massFile) match {
-   case (pom, checksum) if (!pom.file.exists) => DIRTY
-   case (pom, checksum) if (!checksum.file.exists) => CONFLICT
-   case (pom, checksum) => {
-     val sha = new String(MessageDigest.getInstance("SHA").digest( pom.slurp.getBytes ))
-     if( sha == checksum.slurp ) CLEAN
-     else DIRTY
-   }
- }
No comments:
Post a Comment