IO、並び替え
IO and sorting
これまでのコード
// server.go
package main
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
// PlayerStore stores score information about players
type PlayerStore interface {
GetPlayerScore(name string) int
RecordWin(name string)
GetLeague() []Player
}
// Player stores a name with a number of wins
type Player struct {
Name string
Wins int
}
// PlayerServer is a HTTP interface for player information
type PlayerServer struct {
store PlayerStore
http.Handler
}
const jsonContentType = "application/json"
// NewPlayerServer creates a PlayerServer with routing configured
func NewPlayerServer(store PlayerStore) *PlayerServer {
p := new(PlayerServer)
p.store = store
router := http.NewServeMux()
router.Handle("/league", http.HandlerFunc(p.leagueHandler))
router.Handle("/players/", http.HandlerFunc(p.playersHandler))
p.Handler = router
return p
}
func (p *PlayerServer) leagueHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", jsonContentType)
json.NewEncoder(w).Encode(p.store.GetLeague())
}
func (p *PlayerServer) playersHandler(w http.ResponseWriter, r *http.Request) {
player := strings.TrimPrefix(r.URL.Path, "/players/")
switch r.Method {
case http.MethodPost:
p.processWin(w, player)
case http.MethodGet:
p.showScore(w, player)
}
}
func (p *PlayerServer) showScore(w http.ResponseWriter, player string) {
score := p.store.GetPlayerScore(player)
if score == 0 {
w.WriteHeader(http.StatusNotFound)
}
fmt.Fprint(w, score)
}
func (p *PlayerServer) processWin(w http.ResponseWriter, player string) {
p.store.RecordWin(player)
w.WriteHeader(http.StatusAccepted)
}データを保存する
最初にテストを書く
テストを実行してみます
テストを実行するための最小限のコードを記述し、失敗したテスト出力を確認します
成功させるのに十分なコードを書く
Refactor
問題を探す
最初にテストを書く
テストを実行してみます
テストを実行するための最小限のコードを記述し、失敗したテスト出力を確認します
成功させるのに十分なコードを書く
リファクタリング♪
最初にテストを書く
テストを実行してみます
テストを実行するための最小限のコードを記述し、失敗したテスト出力を確認します
成功させるのに十分なコードを書く
リファクタリング♪
最初にテストを書く
テストを実行してみます
成功させるのに十分なコードを書く
より多くのリファクタリングとパフォーマンスの懸念
別の問題
最初にテストを書く
テストを実行してみます
成功させるのに十分なコードを書く
もう1つの小さなリファクタリング
ルールを破っただけではありませんか?プライベートなものをテストしていますか?インターフェイスはありませんか?
プライベート型のテストについて
インターフェース
エラー処理
最初にテストを書く
テストを実行してみます
成功させるのに十分なコードを書く
リファクタリング♪
並べ替え
最初にテストを書く
テストを実行してみます
成功させるのに十分なコードを書く
まとめ
学んだこと
ルール違反
ソフトウェアのある場所
最終更新