複数の引数をまとめて読みやすくするパラメータ•オブジェクト|Parameter Object
記事更新日:2024-02-04

まとめよう

まとめる手段がオブジェクト
同じパラメータの組み合わせが出現する場合は、オブジェクトにすることを検討してください
IMPREMENTATION PATTERNS
If a group of parameters is passed together to many methods, consider making an object

ちなみに、パラメータ(parameter)は厳密に言うと「仮引数」
- parameter(仮引数)
- 関数側での定義
- x, y など名前で表現されたもの
- 値を仮定したものだから仮引数
- argument(実引数)
- 呼び出し側が渡すもの
- 実際に渡す値そのものだから実引数

関数側から見れば parameter objectで、呼び出し側から見れば argument object
パラメータ・オブジェクトとは|Parameter Object

引数をオブジェクトにする手法
必要な情報をまとめて渡す手段
関連するパラメータを1つのオブジェクトにまとめるデザインパターン

デザインパターンとして定着している
パラメータ・オブジェクトの利点

シンプルだし、ミスが減るし、ロジック見直しのきっかけにもなる
- 短くて読みやすい
- 正確な情報がまとまっているから、情報不足などのミスを減らせる
- 新たなロジックに気づける
- 同じ組み合わせ → 関連データとしてのロジック見直し
- 情報数を可変にできる
唯一の懸念点はパフォーマンスの問題だが、ほとんどの場合、問題にならないレベル

利点だけ考えて問題ない
パラメータ・オブジェクトを使うべきとき
同じ組み合わせが何度か登場するとき

たとえば、こんなとき
- 「縦、横、高さ、幅」など、サイズの組み合わせが同じ
- 状態などの情報の組み合わせが同じ

同じ組み合わせなら、オブジェクト候補
単純に、引数を減らしたいとき

同じ組み合わせじゃなく、引数を減らす目的でもOK
引数からオブジェクトを作成して引数の数を減らすのは、不正行為のように見えるかもしれませんが、そうではありません。
Clean code
Reducing the number of arguments by creating objects out of them may seem like cheating, but it’s not.

そもそも3つ以上の引数は多すぎると言われてる
3 つの引数 (triadic) は可能な限り避けるべきです。 3 つ以上(polyadic) は特別な理由がなければ使用すべきではありません
Clean code
Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification—and then shouldn’t be used anyway.

引数の数を減らすのも、大事な目的
パラメータ・オブジェクトを作るときの検討事項
パラメータオブジェクトは、ロジックの重要な拠点になりうる
parameter objects can become important homes for logic.
どの形態を選ぶか
配列、コレクション、key-value型など

状況によって、ふさわしいものが異なる
中身はわかりやすいか
オブジェクトの中身が何であるかが理解しづらくなるのがデメリット
デメリットを最小限にするための工夫が必要

たとえば、こんな工夫
- オブジェクト名やkey名をわかりやすくする
- 格納するものが固定の場合(静的)
- 固定のkey名 / 空のitemで先に初期設定し、オブジェクトの中身を明示する
- あちこちで新規追加しない
- 格納するものが可変の場合(動的)
- できるだけ予測可能なkeyにする
- たとえばテーブルの値を格納するなら、フィールド名をkeyにする等
- できるだけ予測可能なkeyにする
メソッドに変換できるか

パラメータの組み合わせがメソッドになるかもしれない
長いパラメータリストをオブジェクトに置き換えたら、それらがメソッドに変換できるかを検討します
IMPREMENTATION PATTERNS
Once you have replaced the long parameter lists with the parameter object, see if there are bits of code using only the fields in the parameter object that you could turn into methods on the parameter object.

なぜメソッドになるの?
あるデータが複数の関数で使われるなら、互いに強く関連しているという手がかりになります
IMPREMENTATION PATTERNS
The fact that the data appears together in several parameter lists is a blatant clue that they are strongly related.

つまり、オブジェクトがこう語りかけてくる
このデータの組み合わせは強く関連しています
This set of data is strong related.

単純なオブジェクトではなく、新たなロジックが発見できるかも

ソロの歌手ではなく、グループ歌手であるという事実を発見しよう
複数の変数が一緒に渡される場合、1つに命名できる可能性があります
clean code
When groups of variables are passed together, they are likely part of a concept that deserves a name of its own.

「ビートルズの楽曲」を、「ジョンとポールとジョージとリンゴの楽曲」と呼称するのは大変
明確に
1つの名前をつけること

戻り値をまとめる場合は、コレクティング・パラメータ
2024-02-04
編集後記:
この記事の内容がベストではないかもしれません。