Split Temporary Variable
Split Temporary Variable(剖解临时变量)
Summary:
- 你的程序有某个临时变量被赋值超过一次,它既不是循环变量,也不是一个集合用临时变量(collecting temporary variable)。针对每次赋值,创造一个独立的、对应的临时变量。
Tips:
- 如果临时变量承担多个责任,他就应该被替换(剖解)为多个临时变量,每个变量只承担一个责任。同一个临时变量承担两件不同的事情,会令代码阅读者糊涂。
Comments by Allen Lee:
- 当我们添加一个新的函数时,我们把想到的都写进去而没有考虑什么是很平常的,只是有点随性(hacking)。但当这个函数日益膨胀(不断修改和/或添加新的代码),以致其体积过分庞大而妨碍我们的维护工作时,我们就要注意了。
- 很多时候,我们希望使用Replace Temp with Query使得局部变量(local variable)的数据在class内共享,却又因为入选的代码由于临时变量被无故多次赋值时(多数为了方便而把一个临时变量多处使用)无法顺利重构而烦恼时,你就可以考虑先使用Split Temporary Variable把变量的责任划分清楚,再把变量的“喜悦”分享给class的其他成员。
- 不久前,我在学习这个重构原则的时候,产生了一个疑问:既然变量只被赋值一次,为何不干脆把它声明为常量?带着这个疑问,我E-mail了Martin Fowler,以下是我们的通信原文:
以下是我发给Martin的邮件:
Many other temporaries are used to hold the result of a long-winded bit of code for easy reference later. These kinds of variables should be set only once. That they are set more than once is a sign that they have more than one responsibility within the method. Any variable with more than one responsibility should be replaced with a temp for each responsibility. Using a temp for two different things is very confusing for the reader.
So a variable that is only signed once isn't just like a constant? And why should we use variable here? Can we use a constant here instead of variable due to the fact that the variable is only signed once and won't be changed in the future?
I am looking foward to hearing from you!
Yours sincerely,
Allen Lee
Wed., October 20, 2004
Martin给我的回复很简单,仅两句话,却指出我的一个盲点:
constants are usually constant at compile time or at least constant for the length of the program execution. Local variables (in this form) are constant only for the a single execution of the block they are defined in.
- 原来,我对常量的理解停留在仅被赋值一次这种片面层次上。从Martin的回复我们可以知道,常量的值通常是在编译时就决定了。
- 然而,我隐约记得C#提供两种声明变量的方式:readonly和const。它们两个的一个很重要的区别就是,const常量的值必须在编译时决定;而readonly常量的值除了在编译时决定还可以在运行时决定!这下子问题来了,那使用readonly常量不就成了吗?然而,问题远非这么简单,readonly仅能用来修饰class的field!(有关readonly和const的进一步论述,请参见《readonly vs. const [C#]》。)
- 其实,(函数作用域里面的)局部变量数据确实应该储存在变量里面,因为数据是运行时确定的。虽然一个变量仅用来储存一次数据看起来有点浪费,不过让变量有明确的责任制却是让代码重构起来更灵活的前提。