ラムダ式とメソッド参照 質問する

ラムダ式とメソッド参照 質問する

IntelliJ は、ラムダ式をメソッド参照に置き換えることを提案し続けます。

両者の間に客観的な違いはあるのでしょうか?

ベストアンサー1

厳密には必要なかったことが明らかであるにもかかわらず、なぜこの機能を言語に追加したのか、少し説明させてください (すべてのメソッド参照はラムダとして表現できます)。

注意:正解はない「常にラムダではなくメソッド ref を使用する」または「常にメソッド ref ではなくラムダを使用する」と言う人は無視してください。

この質問は、「名前付きクラスと匿名クラスはいつ使用すればよいですか?」という質問と精神的に非常に似ています。そして答えは同じです。読みやすくなったと思ったら確かに、どちらか一方に当てはまるケースもあれば、その中間にグレーゾーンが多数あるケースもあり、判断を下す必要があります。

メソッド参照の理論は単純です。名前は重要メソッドに名前がある場合、最終的にメソッドを呼び出すだけの命令型のコードではなく、名前でメソッドを参照する方が、多くの場合 (常にそうとは限りませんが) より明確で読みやすくなります。

パフォーマンスや文字数のカウントに関する議論は、ほとんどが誤解を招くものなので、無視してください。目標は、何をするかが明確にわかるコードを書くことです。この基準では、メソッド参照が勝つことが非常に多い (ただし常にそうとは限りません!) ため、そのような場合に使用できるように、オプションとしてメソッド参照を含めました。

A key consideration about whether method refs clarify or obfuscate intent is whether it is obvious from context what is the shape of the function being represented. In some cases (e.g., map(Person::getLastName), it's quite clear from the context that a function that maps one thing to another is required, and in cases like this, method references shine. In others, using a method ref requires the reader to wonder about what kind of function is being described; this is a warning sign that a lambda might be more readable, even if it is longer.

Finally, what we've found is that most people at first steer away from method refs because they feel even newer and weirder than lambdas, and so initially find them "less readable", but over time, when they get used to the syntax, generally change their behavior and gravitate towards method references when they can. So be aware that your own subjective initial "less readable" reaction almost certainly entails some aspect of familiarity bias, and you should give yourself a chance to get comfortable with both before rendering a stylistic opinion.

おすすめ記事