Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
読みやすいコード
Search
Takumi Shotoku
December 05, 2019
Technology
1
710
読みやすいコード
Omotesando.rb #53
https://omotesandorb.connpass.com/event/157355/
Takumi Shotoku
December 05, 2019
Tweet
Share
More Decks by Takumi Shotoku
See All by Takumi Shotoku
滅・サービスクラス🔥 / Destruction Service Class
sinsoku
6
1.6k
テストを書かないためのテスト/ Tests for not writing tests
sinsoku
1
200
ドメインの本質を掴む / Get the essence of the domain
sinsoku
2
250
"型"のあるRailsアプリケーション開発 / Typed Rails application development
sinsoku
9
2.6k
Let's get started with Ruby && Rails Tips
sinsoku
0
390
LTの敷居を下げる / Lower the threshold for LT
sinsoku
1
350
CircleCIの高速化🚀 / CircleCI faster
sinsoku
3
1.3k
Railsアプリと型検査 / Rails app and type checking
sinsoku
5
1.4k
💎のつくりかた 2023 / How to make gems 2023
sinsoku
2
360
Other Decks in Technology
See All in Technology
次世代KYC活動報告 / 20250219-BizDay17-KYC-nextgen
oidfj
0
260
急成長する企業で作った、エンジニアが輝ける制度/ 20250214 Rinto Ikenoue
shift_evolve
3
1.3k
転生CISOサバイバル・ガイド / CISO Career Transition Survival Guide
kanny
3
1k
抽象化をするということ - 具体と抽象の往復を身につける / Abstraction and concretization
soudai
19
7.9k
プロセス改善による品質向上事例
tomasagi
2
2.6k
PHPで印刷所に入稿できる名札データを作る / Generating Print-Ready Name Tag Data with PHP
tomzoh
0
110
PHPカンファレンス名古屋-テックリードの経験から学んだ設計の教訓
hayatokudou
2
360
(機械学習システムでも) SLO から始める信頼性構築 - ゆる SRE#9 2025/02/21
daigo0927
0
150
トラシューアニマルになろう ~開発者だからこそできる、安定したサービス作りの秘訣~
jacopen
2
2k
偶然 × 行動で人生の可能性を広げよう / Serendipity × Action: Discover Your Possibilities
ar_tama
1
1.1k
エンジニアのためのドキュメント力基礎講座〜構造化思考から始めよう〜(2025/02/15jbug広島#15発表資料)
yasuoyasuo
17
6.9k
個人開発から公式機能へ: PlaywrightとRailsをつなげた3年の軌跡
yusukeiwaki
11
3k
Featured
See All Featured
Facilitating Awesome Meetings
lara
52
6.2k
The Illustrated Children's Guide to Kubernetes
chrisshort
48
49k
How to Ace a Technical Interview
jacobian
276
23k
The Power of CSS Pseudo Elements
geoffreycrofte
75
5.5k
RailsConf 2023
tenderlove
29
1k
YesSQL, Process and Tooling at Scale
rocio
172
14k
The Language of Interfaces
destraynor
156
24k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
27
1.9k
We Have a Design System, Now What?
morganepeng
51
7.4k
Designing for Performance
lara
604
68k
Templates, Plugins, & Blocks: Oh My! Creating the theme that thinks of everything
marktimemedia
30
2.2k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
6
550
Transcript
読みやすいコード 表参道.rb #53 2019/12/05(Thu) 1
自己紹介 名前: 神速 会社: メドピア株式会社 GitHub: @sinsoku (アイコン右上) Twitter: @sinsoku_listy
(アイコン右下) 2
コードを読みやすく書きたい 3
読みやすいコードとは何か 4
考えてみた • 短いコード • 条件分岐の少ないコード • 適切な命名の変数、クラス、メソッド...etc • メソッド呼び出しのネストが浅い 5
メソッド呼び出しのネストが深い例 def index set_user end private def set_user user_name =
get_user_name_from_api @user = User.find_or_initialize(user_name: user_name) end def get_user_name_from_api api = Sugoi::API.new(token: ENV['SUGOI_TOKEN']) user_name = api.get_user_name convert(user_name) end def convert(user_name) user_name.gsub('-', '_') end 6
浅くした例 def index user_name = api.get_user_name converted_user_name = user_name.gsub('-', '_')
@user = User.find_or_initialize(user_name: converted_user_name) end private def api @api ||= Sugoi::API.new(token: ENV['SUGOI_TOKEN']) end 7
話を戻して... 8
読みやすいコードの条件(主観) • 短いコード • 条件分岐の少ないコード • 適切な命名の変数、クラス、メソッド...etc • メソッド呼び出しのネストが浅い 9
RuboCopでだいたい検出できる • Metrics/AbcSize • Metrics/ClassLength: • Metrics/MethodLength 10
これで読みやすいコードになる! 11
しかし、現実は... # rubocop:disable Metrics/AbcSize Metrics/MethodLength def index # rubocop:enable Metrics/AbcSize
Metrics/MethodLength set_user set_blogs if params[:new] @users = User.where(foo: params[:foo]) .foo .bar .buz elsif params[:create] @users = User.where(foo: params[:foo]).piyo else # ർΕͨͷͰུ end end 12
Metrics/AbcSize を下げるテクニック 1. 変数を定義しない 2. Array(Enumerable)のメソッドを駆使する 3. クラスを抽出する 13
1. 変数を定義しない # bad def count_blogs(users) result = {} users.each
do |user| next unless user.active? result[user.id] = uesr.blogs.size end result end 14
1. 変数を定義しない # good def count_blogs(users) {}.tap do |result| users.each
do |user| next unless user.active? result[user.id] = uesr.blogs.size end end end 15
2. Array(Enumerable)のメソッドを駆使する • if/unlessよりselect/reject # good def count_blogs(users) # active_users
= users.select { |user| user.active? } ͱಉ͡ active_users = users.select(&:active?) {}.tap do |result| active_users.each do |user| result[user.id] = uesr.blogs.size end end end 16
2. Array(Enumerable)のメソッドを駆使する • このケースは to_h で良い # good def count_blogs(users)
users.select(&:active).to_h { |user| [user.id, user.blogs.size] } # ruby 2.5 ͩͱ͜Ε # users.select(&:active).map { |user| [user.id, user.blogs.size] }.to_h end 17
2. Array(Enumerable)のメソッドを駆使する • eachで範囲を-1/+1する必要はない (1..10).to_a #=> [1, 2, 3, 4,
5, 6, 7, 8, 9, 10] (1...10).to_a #=> [1, 2, 3, 4, 5, 6, 7, 8, 9] [:a, :b, :c].each.with_index(1).to_a #=> [[:a, 1], [:b, 2], [:c, 3]] 18
2. Array(Enumerable)のメソッドを駆使する • group_by と transform_values users_per_status = User.find_each.group_by(&:status) #=>
{ "pending" => [<User>, ...], "active" => [<User>, ... } users_per_status.transform_values { |users| users.map(&:user_name) } #=> { "pending" => ["sinsoku", ...], "active" => ["yuki3738", ... } 19
3. クラスを抽出する # app/models/user/ranking.rb class User class Ranking def initialize(user)
@user = user end end def rank score = calculate_score # ུ end private def calculate_score # ུ end end 20
モジュールにするのは # app/models/concerns/rankingable.rb module Rankingable def rank # ུ end
private def calculate_score # ུ end end class User include Rankingable end User.new.private_methods.include?(:calculate_score) #=> true 21
ここから追記 発表に間に合ったのはここまでだった... 22
Class vs Module • Classのprivateメソッドのスコープは狭い • リファクタリングしやすい • Moduleだと影響範囲の調査が少し面倒 •
Moduleは少ないメソッドに依存させるべき • Enumerableは each のみに依存してる • Moduleを上手く使うのは難しい 23
まとめ • RuboCopの指摘はリファクタリングの目安 • 安易に rubocop:disable しない • Arrayのメソッド一覧を読むのがおすすめ •
https://docs.ruby-lang.org/ja/latest/class/Array.html • ModuleよりClassの方がおすすめ 24