First they ignore you
          then they ridicule you
          then they fight you
          then you win
              -- Mahatma Gandhi
          Chinese => English     英文 => 中文             
          隨筆-221  評論-1047  文章-0  trackbacks-0
          Groovy和Java都習(xí)慣使用null來表示“空”這一概念,而對null的操作將引發(fā)NullPointerException(簡寫為NPE),進(jìn)而影響系統(tǒng)的健壯性。為了避免NPE,Option模式應(yīng)運(yùn)而生,通過Option類型來標(biāo)識NPE風(fēng)險,其使用None對象表示“空”,并使用Some對象表示“非空”且持有值對象,最終提升了系統(tǒng)健壯性。

          1.使用Gradle管理項目,通過“gradle init --type groovy-library”生成項目結(jié)構(gòu)
          <項目根目錄>
          │  build.gradle
          │  gradlew
          │  gradlew.bat
          │  settings.gradle

          ├─.gradle
          │  └─2.12
          │      └─taskArtifacts
          │              cache.properties
          │              cache.properties.lock
          │              fileHashes.bin
          │              fileSnapshots.bin
          │              outputFileStates.bin
          │              taskArtifacts.bin

          ├─gradle
          │  └─wrapper
          │          gradle-wrapper.jar
          │          gradle-wrapper.properties

          └─src
              ├─main
              │  └─groovy
              │          Library.groovy
              │
              └─test
                  └─groovy
                          LibraryTest.groovy

          2.編輯build.gradle,管理項目依賴
          /*
           * This build file was auto generated by running the Gradle 'init' task
           * by '山風(fēng)小子' at '16-8-13 下午3:03' with Gradle 2.12
           *
           * This generated file contains a sample Groovy project to get you started.
           * For more details take a look at the Groovy Quickstart chapter in the Gradle
           * user guide available at 
          https://docs.gradle.org/2.12/userguide/tutorial_groovy_projects.html
           
          */

          // Apply the groovy plugin to add support for Groovy
          apply plugin: 'groovy'

          // In this section you declare where to find the dependencies of your project
          repositories {
              // Use 'jcenter' for resolving your dependencies.
              
          // You can declare any Maven/Ivy/file repository here.
              maven { url 'https://dl.bintray.com/danielsun1106/generic/' } // 新增代碼
              jcenter()
          }

          // In this section you declare the dependencies for your production and test code
          dependencies {
              // We use the latest groovy 2.x version for building this library
              compile 'org.codehaus.groovy:groovy-all:2.4.7' // 新增代碼

              compile 'com.groovyhelp:groovy-option-support:1.0.1' // 新增代碼
          }

          // 新增代碼
          task run(type: JavaExec, dependsOn: 'classes') {
              classpath = sourceSets.main.runtimeClasspath
              main = "Library"
          }

          3.至此環(huán)境已準(zhǔn)備完畢,編輯src/main/groovy/Library.groovy,并執(zhí)行“gradle run”以開始我們Option模式體驗之旅
          /*
           * This Groovy source file was auto generated by running 'gradle buildInit --type groovy-library'
           * by '
          山風(fēng)小子' at '16-8-13 下午3:03' with Gradle 2.12
           *
           * @author 
          山風(fēng)小子, @date 16-8-13 下午3:03
           
          */
          class Library {
              public static void main(String[] args) {
                      println "*********** Option模式體驗之旅 *************"
                          
                          def m = new HashMap() {
                              {
                                  putAll([a: 1, b: 2, c: 3]); // 初始化
                              }

                              @Override
                              public Option get(Object key) { // 覆蓋HashMap的get方法,以返回Option對象,該對象通過Option.$new方法創(chuàng)建
                                  return Option.$new(super.get(key));
                              }
                          }

                          // 由于get方法已通過Option標(biāo)示了NPE風(fēng)險,所以調(diào)用者有意識地使用$switch方法來分情況處理
                          m.get('b').$switch {
                                  // 如果get的返回結(jié)果為Some(即“非空”),則執(zhí)行該閉包內(nèi)容
                              println "b對應(yīng)的值: $it";
                          } {
                              // 如果get的返回結(jié)果為None(即“空”),則執(zhí)行該閉包內(nèi)容
                              println "找不到b對應(yīng)的值";
                          }
                          
                          // $switch的另外一種使用方式,與上述方式相似
                          println 'b的查找結(jié)果:' + m.get('b').$switch { return it /* 返回b對應(yīng)的值 */ } { return 0 /* 如果沒有找到b,則返回0 */ }
                          
                          // 嘗試查找一個不存在的key(比如d)
                          m.get('d').$switch {
                              println "d對應(yīng)的值: $it";
                          } {
                              println "找不到d對應(yīng)的值";
                          }
                          
                          // 雖然是Option對象,但可以將其視作原始對象并訪問其方法及屬性
                          println """m.get('a').intValue()執(zhí)行結(jié)果: ${m.get('a').intValue()}"""
                          
              }
          }

          執(zhí)行結(jié)果:
          D:\_LAB>gradle run
          :compileJava UP-TO-DATE
          :compileGroovy
          :processResources UP-TO-DATE
          :classes
          :run
          *********** Option模式體驗之旅 *************
          b對應(yīng)的值: 2
          b的查找結(jié)果:2
          找不到d對應(yīng)的值
          m.get('a').intValue()執(zhí)行結(jié)果: 1

          BUILD SUCCESSFUL

          Total time: 7.803 secs

          更多例子可以查看:https://github.com/daniellansun/groovy-option-support/blob/master/src/test/groovy/groovy/lang/OptionTest.groovy
          groovy-option-support項目主頁:https://github.com/daniellansun/groovy-option-support

          附:朝花夕拾——Groovy & Grails
          posted on 2016-08-13 16:17 山風(fēng)小子 閱讀(2294) 評論(0)  編輯  收藏 所屬分類: Groovy & Grails
          主站蜘蛛池模板: 江永县| 青海省| 远安县| 石渠县| 汉阴县| 铁力市| 监利县| 都匀市| 布尔津县| 金湖县| 永新县| 南江县| 凤庆县| 肃宁县| 英超| 新源县| 雅安市| 兴宁市| 会昌县| 大连市| 南宫市| 旬邑县| 鄂州市| 普陀区| 兰州市| 宜兴市| 疏附县| 平江县| 班玛县| 营口市| 南部县| 教育| 太和县| 鹤峰县| 探索| 延庆县| 时尚| 玛纳斯县| 清水河县| 桐柏县| 秭归县|