2013-03-21 68 views
1

在下面的代碼中,有很多冗餘代碼,我在左側執行所有三個事實的相同操作。在右側,我也有相同的塊。我如何處理這種冗餘?刪除給定midje測試中的冗餘代碼

(facts "Data is grouped by the given keys." 
     (fact "The grouping keys are a subset of the :month/:day keys in data" 
      (group-data data :day) => (fn [d] 
              (let [months (map :day data) 
               grouped-by-keys (keys d)] 
              (subset? (set grouped-by-keys) (set months))))) 
     (fact "All the grouping keys are distinct" 
      (group-data data :day) => (fn [d] 
              (let [months (map :day data) 
               grouped-by-keys (keys d)] 
              (apply distinct? grouped-by-keys)))) 
     (fact "All the distinct keys from data are present in grouping keys" 
      (group-data data :day) => (fn [d] 
              (let [months (map :day data) 
               grouped-by-keys (keys d)] 
              (empty? (difference (set months) (set grouped-by-keys))))))) 

回答

1

宏可以幫助:

(defmacro day-facts [facts] 
    (let [f (fn [[name expr]] 
      `(~'fact ~name 
        (~'group-data ~'data :day) ~'=> (fn [~'d] 
                 (let [~'months (map :day ~'data) 
                  ~'grouped-by-keys (keys ~'d)] 
                 ~expr))))] 
    `(~'facts "Data is grouped by the given keys." 
       [email protected](map f facts)))) 


(day-facts [["The grouping keys are a subset of the :month/:day keys in data" (subset? (set grouped-by-keys) (set months))] 
      ["All the grouping keys are distinct" (apply distinct? grouped-by-keys)] 
      ["All the distinct keys from data are present in grouping keys" (empty? (difference (set months) (set grouped-by-keys)))]])