Skip to content

Instantly share code, notes, and snippets.

@you21979
Last active May 31, 2016 03:59
Show Gist options
  • Save you21979/4743726e781fceea88abcd69d3ba4eed to your computer and use it in GitHub Desktop.
Save you21979/4743726e781fceea88abcd69d3ba4eed to your computer and use it in GitHub Desktop.

前提条件を整えないと呼び出せない関数

var config = require("./config");
var calcRate = function(input){
  var rate = config['xxrate'];
  return min(max(0, rate * input), 100);
}
var main = function(){
  console.log(calcRate(150));
}

問題点

  • パラメータを関数の引数ではなくグローバルに置かれたconfigテーブルを参照するので単体での境界値テストが不可能
  • 無意味に依存関係を構築しているためモジュール性が悪い

修正後

var config = require("./config");
var calcRate = function(rate, input){
  return min(max(0, rate * input), 100);
}
var main = function(){
  console.log(calcRate(config['xxrate'], 150));
}

時間によって結果が異なる関数

var getMessage = function(){
    var date = new Date();
    var h = date.getHours();
    if(h > 5 && h < 10){
      return "good morning";
    }else{
      return "hello";
    }
}
var main = function(){
  console.log(getMessage());
}

問題点

  • パラメータがなく時間によって振る舞いが変わるので単体でのテストが不可能

修正後

var getMessage = function(date){
    var h = date.getHours();
    if(h > 5 && h < 10){
      return "good morning";
    }else{
      return "hello";
    }
}
var main = function(){
  console.log(getMessage(new Date()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment