7

重构改善既有代码的设计

 1 year ago
source link: http://muyunyun.cn/blog/wqq5fekb/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

重构改善既有代码的设计

本文是重构改善既有代码的设计阅读笔记

重构与性能优化

  • 重构: 目标是更易理解;(面向人)
  • 性能优化: 目标是使程序运行更快;(面向机器)

重构的好处

  1. 帮助快速找到 bug
  2. 提高编程速度

提炼函数(Extract Function)

背景: 一整段函数不利于阅读; 方式: 按语义进行重构, 将不利于阅读的函数其拆分成小份, 并给它们取上恰当的名字以便于阅读;

内联函数(Inline Function)

背景: 函数拆得太细, 和提炼函数相反的一种重构手段; 方式: 可以逐行替换;

函数重命名

当希望修改的函数名存在大量使用时, 可以采用渐进式的做法(旧代码调用旧函数, 旧函数调用新函数)对函数重命名:

function circum(radius) {
return 2 * Math.PI * radius
function circum(radius) {
return circumference(radius)
function circumference(radius) {
return 2 * Math.PI * radius

如何给一个 function 起好名字: 先给 function 写一段注释, 再把该注释压缩为函数的名字。

统一访问原则

class Test {
return 'a'
get b() {
return 'b'
var test = new Test()
test.a() // 'a'
test.b // 'b'

推崇 get 的写法, 用户调用该类的时候无需关系是字段还是推演计算的值。

当前阅读到: 拆分阶段。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK