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
730
読みやすいコード
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
Automatically generating types by running tests
sinsoku
2
9.7k
滅・サービスクラス🔥 / Destruction Service Class
sinsoku
8
2.3k
テストを書かないためのテスト/ Tests for not writing tests
sinsoku
1
240
ドメインの本質を掴む / Get the essence of the domain
sinsoku
2
290
"型"のあるRailsアプリケーション開発 / Typed Rails application development
sinsoku
10
2.8k
Let's get started with Ruby && Rails Tips
sinsoku
0
430
LTの敷居を下げる / Lower the threshold for LT
sinsoku
1
380
CircleCIの高速化🚀 / CircleCI faster
sinsoku
3
1.4k
Railsアプリと型検査 / Rails app and type checking
sinsoku
5
1.5k
Other Decks in Technology
See All in Technology
Абьюзим random_bytes(). Фёдор Кулаков, разработчик Lamoda Tech
lamodatech
0
330
Microsoft Build 2025 技術/製品動向 for Microsoft Startup Tech Community
torumakabe
2
250
AWS テクニカルサポートとエンドカスタマーの中間地点から見えるより良いサポートの活用方法
kazzpapa3
2
500
Snowflake Summit 2025 データエンジニアリング関連新機能紹介 / Snowflake Summit 2025 What's New about Data Engineering
tiltmax3
0
300
VISITS_AIIoTビジネス共創ラボ登壇資料.pdf
iotcomjpadmin
0
160
20250623 Findy Lunch LT Brown
3150
0
840
AWS Summit Japan 2025 Community Stage - App workflow automation by AWS Step Functions
matsuihidetoshi
1
230
Windows 11 で AWS Documentation MCP Server 接続実践/practical-aws-documentation-mcp-server-connection-on-windows-11
emiki
0
910
Observability infrastructure behind the trillion-messages scale Kafka platform
lycorptech_jp
PRO
0
130
ローカルLLMでファインチューニング
knishioka
0
150
~宇宙最速~2025年AWS Summit レポート
satodesu
1
1.8k
Agentic DevOps時代の生存戦略
kkamegawa
1
1.3k
Featured
See All Featured
Adopting Sorbet at Scale
ufuk
77
9.4k
The Invisible Side of Design
smashingmag
299
51k
Bash Introduction
62gerente
614
210k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
34
3k
Writing Fast Ruby
sferik
628
61k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
233
17k
Designing for humans not robots
tammielis
253
25k
A designer walks into a library…
pauljervisheath
206
24k
Creating an realtime collaboration tool: Agile Flush - .NET Oxford
marcduiker
30
2.1k
Measuring & Analyzing Core Web Vitals
bluesmoon
7
490
4 Signs Your Business is Dying
shpigford
184
22k
Practical Tips for Bootstrapping Information Extraction Pipelines
honnibal
PRO
20
1.3k
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