正式开启『 优雅的 Ruby 』的学习模式!
上回提到我们要用这本书来快乐学习,
透过重构的技巧进行修改、维护我们的程序码。
重构是指对软件代码进行更动以增加可读性或者简化结构,但是不影响功能和输出结果。
重点来了,
进行重构前必须先完成程序语言。
所以;你需要先学好如何把你的每段 Code 依照逻辑、根据、方法呈现等『方法』 进行整理,
才能执行重构。
最常用以下四种的归类方法:
输入处理 (collecting input);
功能实现 (performing work);
输出处理 (delivering output);
失败处理 (handling failures);
其他方法如诊断(diagnostics)、清理(cleanup),为特殊背景下使用,但请先记住。(未来文章介绍)
(此段模拟於 Ruby 一书经典范例)
def location(item, value)
sub_ttile = get_sub_ttile(item, value)
if(sub_ttile.length==0)
raise BobArticle::AnalysisError, "The '#{item,to_s}''#{value,to_s}'does not have any rows in the analysis table"
else
first_row = sub_table[0]
case item
when :class
BobArticle::Location.get(first_row.file_path, first_row.class_name,nil)
when :method
BobArticle::Location.get(first_row.file_path, first_row.class_name, first_row.method_name)
when :file
BobArticle::Location.get(first_row.file_path, fnil, nil)
else
raise ArgumentError, "Item must be :class, :method, or :file"
end
end
end
这里不急探讨这code的目的是什麽,先套入上述四个归类方法进行拆分,
先学会分析、归类再与结果呈现进行比对。
首先;
这是取得『输入』:
sub_ttile = get_sub_ttile(item,value)
若发生错误、数据不存在时,则抛出异常:
if(sub_ttile.length==0)
raise BobArticle::AnalysisError,"The '#{item,to_s}''#{value,to_s}'does not have any rows in the analysis table"
若数据在,则直接获取数据:
else
first_row = sub_table[0]
该方法的核心功能:
case item
when :class
BobArticle::Location.get(first_row.file_path,first_row.class_name,nil)
when :method
BobArticle::Location.get(first_row.file_path,first_row.class_name,first_row.method_name)
when :file
BobArticle::Location.get(first_row.file_path,fnil,nil)
最後的失败处理:
else
raise ArgumentError,"Item must be :class, :method, or :file"
比照最初;
def location(item,value)
sub_ttile = get_sub_ttile(item,value) #输入处理
--------------------------------------------------
if(sub_ttile.length==0)
、、、
else #失败处理
--------------------------------------------------
first_row = sub_table[0]
case item
when :class
、、、
when :method
、、、
when :file
、、、 #功能实现
--------------------------------------------------
else
、、、
end
end
end
上述表达衍生出的问题就是:
else (第6行) end (第20行) 变成是异常处理。表示如果没有异常的情下,这段 if 的程序码外层的 else、 end 是没有意义的。
功能分类相杂,虽有输入处理、失败处理、功能实现、异常处理但不同部分参杂一起容易模糊重点分析。
练习使用归纳方式整理程序码,如同我们在栽植一样的细心呵护~
让我们重新整理顺序:
易於理解和维护、更少的bug 且能更灵活的适应需求变化,找回初衷。
好的故事表达带你上天堂,
越能符合语意的目的,表示我们离资优生笔记更近一点!
那今天就先学习到这,
但务必牢记四个归类方法,不论是今後铁人文章用还是永久的学习!
我们绝对都会经常不断地重复使用到、甚至当作练习的基础。
>>: 【D7】取得历史资料:三大法人-区分期货与选择权二类
购物网站能加入购物车後,就只剩结帐功能啦!!不过串接金流的方面与本主题较无关,所以这边只会做完结帐的...
什麽是 head? 我们在 commit 版本时,其实是将档案 commit 到一条 branch(...
https://github.com/kaichiachen/python-simple-objec...
前情提要 由於在POST /v1/users/ 时我们会需要透过smtp寄出通知信再回respons...
这次就要来练习上次学习的switch 这边我想了个题目来练习 那现在就开始练习程序码吧! 题目:利用...