SQL Antipatterns ch23 See No Evil
- See No Evil
- Objective: Write Less Code
- Antipattern: Making Bricks Without Straw
- How to Recognize the Antipattern
- Legitimate Uses of the Antipattern
- Solution: Recover from Errors Gracefully
- 英語
See No Evil
Troubleshooting code is already hard enough.
Don't hinder yourself by doing it blind.
- APIの戻り値や例外を見ずに製品のせいにする
Objective: Write Less Code
- コードを短くする理由
- うわべの理由
- エレガントさ
- まっとうな理由
- 開発をすばやく終えられる
- テスト・ドキュメント・レビュー対象の量が減る
- 不具合が減る
- うわべの理由
Antipattern: Making Bricks Without Straw
Diagnoses Without Diagnostics
<?php $dbh = new PDO('mysql:dbname=test;host=db.example.com', 'dbuser', 'dbpassword'); $sql = 'SELECT bug_id, summary, date_reported FROM Bugs WHERE assigned_to = ? AND status = ?'; $stmt = $dbh->prepare($sql); $stmt->execute(array(1, 'OPEN')); $bug = $stmt->fetch();
- 簡潔
- 例外フロー無視しまくり
- PDO::construct()は失敗するとPDOException送出
- コネクション情報を間違えた場合など
- PDO::prepareは失敗するとfalseを返す
- PDOStatement::execute()も失敗するとfalseを返す
- 制約違反
- アクセス権違反
- PDOStatement::fetch()も失敗するとfalseを返す
- RDBMSへの接続失敗など
- PDO::construct()は失敗するとPDOException送出
- 例外フローを無視する人の言い分
- 起こらないはずのことを書いたところでコードに何も加わらない
- 余分のコードが繰り返され、醜く読みづらくなる
- エンドユーザーはコードを読みませんよ
Lines Between the Reading
How to Recognize the Antipattern
- IDEが怒ってくれたりする
- こんなのが聞こえてきたら注意:
Legitimate Uses of the Antipattern
- アプリケーション終了間際のclose()とか
- アプリケーション終了とともに自動的に後始末してもらえる
- 例外を上流で処理してほしい場合
Solution: Recover from Errors Gracefully
- ダンスでステップをしくじった際に優雅に復帰するように
Maintain the Rhythm
- 例外とか戻り値とかちゃんと検査する
Retrace Your Steps
- SQL構築処理ではいったん変数に受けよ
- APIやprepareに直接渡さない
- SQL出力をアプリケーションの出力以外の場所に吐き出す
- ログファイル
- IDEデバッガコンソール
- ブラウザ拡張
- HTMLコメントには書き出すな
- ハッカーへの情報提供
- ORM等に閉じ込められてSQLを見れない場合は?
- DB製品自体のSQLログ機能を使う
英語
- making bricks without straw
- 必要な材料なしで仕事をする
- 昔はレンガに藁を混ぜていたらしい
- 必要な材料なしで仕事をする
- intersperse
- 散りばめる
- diagnose
- 診断
- diagnostics
- 診断技術/器具
- consolation
- 慰め