代码重构

代码重构(英語:code refactoring)指对软件代码做一些改动以增加可读性或者简化代码结构而不影响输出结果。

软件重构需要借助重构工具完成,重构工具能够修改代码同时修改所有引用该代码的地方。在极限编程的方法学中,重构需要单元测试来支持。

重构代码

图一
图二

软件工程学裡,重构代码一词通常是指在不改变代码的外部行为情况下而修改源代码。在极限编程或其他敏捷方法学中,重构常常是软件开发中的一部分:开发者轮流增加新的测试和功能,并重构代码来增进代码间的清晰性和一致性。同时,自动化的单元测试保证了重构后的代码仍然能够正常运作。

重构既不修正错误,也不增加新的功能。它的目的是用于提高代码的可读性或者改变代码内部结构设计或者刪除死碼,使其在将来更容易进行维护和开发。重构代码可以存在于结构层面或是语意层面,但前提是不影响代码在转换前后的功能。一种进行重构的典型案例是:一个程序在现有的逻辑结构下难以加入新的功能,因此开发人员可能会对代码进行重构,以便日后继续开发。

一个重构的小范例是修改一个变量的名称使其具有更明确的含义,例如从单个字母的「i」重构为「interestRate」(利率,图一)。一个较复杂的重构的例子是把一段if区块中的代码变为一个子程序(图二)。更复杂一点的重构是用多态性来替换if 条件式。進一步還可重新设计程序的算法。在重构中最关键的是去有意地「清理」代码,把不同的功能分开,然后对重构后的代码进行测试(任何对代码的编辑都有可能引发错误)。新的实现方法需要切合实际地改善现有设计,并且不改变原软件的功能或行为。

难点

代码重构也面临诸多的挑战。首先,对重构长远的影响需要在重构后才能进行深入研究和追踪。其次,重构某些底层业务逻辑或是数据库架构几乎是不可能的。最后,对接口造成影响的重构可能造成程式開發上的困境。例如,程序员若改变某接口中的方法名称,除非他或她要对所有客户端中连结到旧方法名的参考都加以编辑,否则就只能继续维护使用旧方法名的接口,并另外建立旧名对新名的映射。

源流

首先使用「重构」一辞于出版文献是于一篇文章:《Refactoring: An Aid in Designing Application Frameworks and Evolving Object-Oriented Systems, Proceedings of the Symposium on Object Oriented Programming Emphasizing Practical Applications (SOOPPA)》,1990年9月,由William F. Opdyke与Ralph E. Johnson联名出版[1]。William Opdyke的博士论文于「重构:物件导向框架」,伊利诺大学,1992年出版[2]。「重构」术语几乎至其后确定。

重构这个术语是从数字多项式因式分解类比而来[3]。如,x2 − 1可以被分解为(x + 1)(x − 1),这样更好的整理并展示了式子的性质(例如式子拥有两个+1和−1)。同样,在软件重构中,结构上的改变通常会揭示原代码中曾经「隐藏」的内部结构。

上面多项式的例子很好地展示了「重构」的思路。但是,一个多项式的不同表示形式并没有优劣之分,它们展现了多项式的不同性质。在不同情况下适合的表达形式不同,并且还会随着使用者的个人习惯或理解变化。这个问题于软件开发领域亦然:个别程式员可能对某既定演算法的理想结构会有不同的意见。

重构方法简单列表

下面是不完整的代码重构清单。长一点的清单可以在福勒的重构书找到。因为研究者们继续努力不懈的发明以及实现重构,完整清单可能永远都不存在。

  • 封装成员变量英语Field encapsulation(Encapsulate Field)—将仅限于本类使用的变量重写成私有(private)成员变量,并提供访问方法(accessor method)。这种重构方式可以将与外部调用者无关的变量隐藏起来,减少代码的耦合性,并减少意外出错的概率。
  • 提取方法(Extract Method)—意思是将大段代码中的一部分提取后,构成一个新方法。这种重构可以使整段程序的结构变得更清晰,从而增加可读性。这也对函数(Function)通用。
  • 类一般化英语Type generalization(Generalize Type)—将多个类/函数共用的类型抽象出可以公用的基类(base class),然后利用多态性追加每个类/函数需要的特殊函数。这种重构可以让结构更加清晰,同时可以增加代码的可维护性。
  • 函数归父(Pull Up)—或译函数上移,指的是方法从子类移动到父类。
  • 函数归子(Push Down)—或译函数下移,指的是方法从父类移动到子类。
  • 方法更名英语Rename_method(Rename Method)—将方法名称以更好的表达它的用途。
重构方法 重构前 重构后
封装成员变量
 
class SomeClass {
public int memberA;
...
}
class SomeClass { 
private int memberA; 
public int getMemberA();
public void setMemberA(int a);
...
}
方法提取
void Process(MyDataSet mds) 
{   
 // Step 1 ... 
 int result = 0;  
 if (mds.isReady) 
 {  
  int data1 = mds.param[0]; 
  int data2 = mds.param[1];  
  // Preprocess... 
  result = data1 % data2;  
 } 
 // Step 2... 
}
void Process(MyDataSet mds)
{  
 // Step 1 ... 
 int result = 0;  
 if (mds.isReady) 
  result = CalculateMDS(mds.param[0], mds.param[1]);  
 // Step 2 ... 
}      

int CalculateMDS(int data1, int data2)  
{ 
  // Preprocess...  
  return data1 % data2; 
}
一般化类型
class Rectangle {
  private:
  int w, h;
  public:
  double Area(){
    return w*h;
  }
}
class Triangle {
  private:
  int w, h;
  public:
  double Area(){
    return w*h/2;
  }
}
class Polygon {
  private:
  int w, h;
  public:
  virtual double Area() = 0;
}
class Rectangle : public Polygon {
  double Area(){
  return w*h;
  }
}
class Triangle : public Polygon {
  double Area() {
    return w*h/2;
  }
}
方法更名
public double f(double m, double a);
public double calculateForce(double mass, double acceleration);

代码重构自动化

许多软件编辑器与整合环境支援重构自动化,又称为重构浏览器。枚举如下:

硬件重构

尽管代码重构一词最初只用于软件代码的重构,但近年来,硬件描述语言也出现了相应的代码重构的概念。硬件重构(hardware refactoring)是对硬件描述语言中的代码进行重构的简称。由于一般认为硬件描述语言与传统编程语言有较大的区别[4],因此硬件重构被视为与传统的代码重构不同的领域。

研究者已经提出了模拟电路硬件描述语言(如VHDL-AMS)所使用的自动化重构方法[5]。根据他们的研究,硬件重构会在保持原本代码的仿真结果的同时,增进行为模型的可理解性、可扩展性和可重用性,并使得后续自动化编译过程的逻辑综合步骤可以产生更加符合预期的结构表示。此外,Synopsys公司的Mike Keating也研究了手动进行的数字电路硬件描述语言的重构[6][7]。他所研究的目标是使复杂的硬件系统更易于理解,从而提高设计人员的生产力。

注释

参考文献

引用

  1. ^ 存档副本 (PDF). [2007-11-10]. (原始内容 (PDF)存档于2007-04-18). 
  2. ^ 存档副本. [2007-11-10]. (原始内容存档于2018-09-20). 
  3. ^ 英文重构(refactor)为“重新”(re-)与“(因式)分解”(factor)两单词的结合
  4. ^ 硬件描述语言. 维基百科,自由的百科全书. 2020-05-11 (中文). 
  5. ^ Kaiping Zeng; Huss, S.A. Architecture Refinements by Code Refactoring of Behavioral VHDL-AMS Models. 2006 IEEE International Symposium on Circuits and Systems (IEEE). doi:10.1109/iscas.2006.1692875. 
  6. ^ Golovchenko, E.A. Tutorial: the challenges of designing long-haul WDM systems. Optical Fiber Communication Conference and Exhibit (Opt Soc. America). doi:10.1109/ofc.2002.1036216. 
  7. ^ Keating, Michael; Bricaud, Pierre. Reuse Methodology Manual for System-on-a-Chip Designs. 1998. doi:10.1007/978-1-4757-2887-3. 

來源

书籍

外部链接

参见

Read other articles:

Pour les articles homonymes, voir Secrétaire à l'Intérieur. Ne doit pas être confondu avec Secrétaire à la Sécurité intérieure des États-Unis. Secrétaire à l'Intérieur des États-Unis(en) United States Secretary of the Interior Sceau du département de l'Intérieur des États-Unis. Titulaire actuelleDeb Haalanddepuis le 16 mars 2021(3 ans et 23 jours) Création 3 mars 1849 Mandant Président des États-UnisConfirmé par le Sénat Premier titulaire Thomas Ewing Rémuné...

 

Disambiguazione – Se stai cercando l'attore e regista teatrale, vedi Giovanni Calò (attore). Questa voce sugli argomenti pedagogisti e politici italiani è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. Giovanni Calò Sottosegretario di Stato per le Antichità e le Belle Arti al Ministero dell'Istruzione PubblicaDurata mandato26 febbraio 1922 –1 agosto 1922 PresidenteLuigi Facta Legisl...

 

Classic Loire Atlantique 2017 GénéralitésCourse18e Classic Loire-AtlantiqueCompétitionsUCI Europe Tour 2017 1.1Coupe de France de cyclisme sur routeDate18 mars 2017Distance182,8 kmPays FranceLieu de départLa Haie-FouassièreLieu d'arrivéeLa Haie-FouassièreÉquipes17Partants128Arrivants96Vitesse moyenne41,184 km/hSite officielSite officielRésultatsVainqueur Laurent Pichon (Fortuneo-Vital Concept)Deuxième Thomas Boudat (Direct Énergie)Troisième Hugo Hofstetter (Cofidis, Solutions Cr�...

Mark Viduka Informasi pribadiNama lengkap Mark Anthony VidukaTanggal lahir 9 Oktober 1975 (umur 48)Tempat lahir Melbourne, AustraliaTinggi 1,88 m (6 ft 2 in)Posisi bermain PenyerangInformasi klubKlub saat ini Free AgentKarier senior*Tahun Tim Tampil (Gol)1993–1995 Melbourne Knights 48 (40)1995–1998 Croatia Zagreb 84 (40)1998–2000 Celtic 37 (30)2000–2004 Leeds United 130 (59)2004–2007 Middlesbrough 72 (26)2007–2009 Newcastle United 38 (7)Total 409 (202)Tim nasi...

 

5-orthoplex Cantellated 5-orthoplex Bicantellated 5-cube Cantellated 5-cube 5-cube Cantitruncated 5-orthoplex Bicantitruncated 5-cube Cantitruncated 5-cube Orthogonal projections in B5 Coxeter plane In five-dimensional geometry, a cantellated 5-orthoplex is a convex uniform 5-polytope, being a cantellation of the regular 5-orthoplex. There are 6 cantellation for the 5-orthoplex, including truncations. Some of them are more easily constructed from the dual 5-cube. Cantellated 5-orthoplex Cant...

 

Bukhori YusufBukhori Yusuf sebagai Calon Anggota Legislatif DPR RI dari Partai Keadilan Sejahtera untuk Pemilihan Umum Legislatif tahun 2019 Anggota Dewan Perwakilan RakyatRepublik IndonesiaMasa jabatan1 Oktober 2019 – Mei 2023Perolehan suara52.790 (2019)[1]PenggantiWisnu Wijaya Adi PutraDaerah pemilihanJawa Tengah IMasa jabatan1 Oktober 2009 – 30 September 2014Daerah pemilihanSumatera Selatan II Informasi pribadiLahir5 Maret 1965 (umur 59)Jepara, Jawa Tenga...

Перуанский анчоус Научная классификация Домен:ЭукариотыЦарство:ЖивотныеПодцарство:ЭуметазоиБез ранга:Двусторонне-симметричныеБез ранга:ВторичноротыеТип:ХордовыеПодтип:ПозвоночныеИнфратип:ЧелюстноротыеГруппа:Костные рыбыКласс:Лучепёрые рыбыПодкласс:Новопёрые �...

 

Education for awareness of and influence on the attitude of health The examples and perspective in this article deal primarily with the United States and do not represent a worldwide view of the subject. You may improve this article, discuss the issue on the talk page, or create a new article, as appropriate. (April 2020) (Learn how and when to remove this message) Part of a series onPublic health Outline Subfields Community health Dental public health Environmental health Epidemiology Health...

 

American politician For other people named Donald Parsons, see Donald Parsons. Don ParsonsMember of the Georgia House of RepresentativesIncumbentAssumed office January 9, 1995Preceded bySteven C. ClarkConstituency40th district (1995–2003)29th district (2003–2005)42nd district (2005–2013)44th district (2013–present) Personal detailsBornDonald Lee Parsons (1947-07-21) July 21, 1947 (age 76)NationalityAmericanPolitical partyRepublican (1994–present)Other politicalaffiliationsD...

Outside of the basilica The Basilica di San Giulio is a Roman Catholic church on the small Isola San Giulio in the center of Lake Orta, province of Novara, north-western Italy. It has the status of a minor basilica.[1] Although the island is part of the Orta San Giulio municipality, the basilica belongs to the San Giacomo parish, including the island and a portion of the west coast of the lake in San Maurizio d'Opaglio municipality. History According to tradition, it was the hundredth...

 

Torneo Federal A Campeonato Argentino de Futebol de 2023 – Terceira Divisão (Torneo Federal A) Terceira Divisão do Campeonato Argentino de 2023XI temporada da Torneo Federal A Participantes 36 times Organização CFFA (AFA) Período 10 de março — 26 de novembro ← 20222024 → O Torneo Federal A do Campeonato Argentino de Futebol de 2023, também conhecido simplesmente como Torneo Federal A de 2023, é a 11.ª temporada do Torneo Federal A, certame equivalente à terceira divisão do...

 

Rule of thumb for estimating a decompression schedule for a given set of breathing gases Ratio decompression (usually referred to in abbreviated form as ratio deco) is a technique for calculating decompression schedules for scuba divers engaged in deep diving without using dive tables, decompression software or a dive computer. It is generally taught as part of the DIR philosophy of diving promoted by organisations such Global Underwater Explorers (GUE) Innerspace Explorers (ISE) and Unified...

2023 UEFA European Under-19 ChampionshipKampjonat Ewropew 2023 ta' Taħt id-19-il senaTournament detailsHost countryMaltaDates3–16 JulyTeams8 (from 1 confederation)Venue(s)4 (in 3 host cities)Final positionsChampions Italy (4th title)Runners-up PortugalTournament statisticsMatches played15Goals scored49 (3.27 per match)Attendance20,539 (1,369 per match)Top scorer(s) Víctor Barberà(4 goals)Best player(s) Luis Hasa[1]← 2022 2024 → Inte...

 

Video game series Video game seriesChocoboThere is no unified logo for the series; this logo was used in Chocobo's Mystery Dungeon Every Buddy!Publisher(s)Square, Square EnixArtist(s)Toshiyuki ItahanaFirst releaseChocobo's Mysterious DungeonDecember 23, 1997Latest releaseChocobo GPMarch 10, 2022Parent seriesFinal Fantasy The Chocobo series is part of the Final Fantasy franchise owned by Square Enix. A spin-off series meant to have more child and casual gamer appeal than the main games, it spa...

 

Not to be confused with Avro Tudor. Avro 621 Tutor Avro Type 621 Tutor of the Shuttleworth Collection Role TrainerType of aircraft National origin United Kingdom Manufacturer Avro Designer Roy Chadwick First flight September 1929 Introduction 1933 Retired 1941 Primary user Royal Air Force Number built 606 Variants Avro 626, PWS-18 The Avro Type 621 Tutor[1][2] is a two-seat British radial-engined biplane from the interwar period. It was a simple but rugged basic trainer t...

  لمعانٍ أخرى، طالع هاواي (توضيح). هاواي    علم شعار الشعار:(بالهاوائية: Ua Mau ke Ea o ka ʻĀina i ka Pono)‏ (31 يوليو 1843–)    الإحداثيات 21°30′N 158°00′W / 21.5°N 158°W / 21.5; -158   [1] تاريخ التأسيس 21 أغسطس 1959  سبب التسمية هاواي  تقسيم إداري  البلد الولايات الم...

 

2022 by-elections in Zimbabwe 2022 Zimbabwean parliamentary by-election ← 2018 26 March 2022 2023 → 28 of the 270 seats in the House of Assembly   Majority party Minority party Third party   Leader Emmerson Mnangagwa Nelson Chamisa Douglas Mwonzora Party ZANU–PF CCC MDC Alliance Last election 179 seats, 52.35% New Party 88 seats, 34.72% Seats after 181 19 68 Seat change 2 19 20   Fourth party   Leader Ambrose Mutinhiri Party National ...

 

John F. Follett John Fassett Follett (* 18. Februar 1831 bei Enosburgh, Vermont; † 15. April 1902 in Cincinnati, Ohio) war ein US-amerikanischer Politiker der Demokratischen Partei. Von 1883 bis 1885 war er Mitglied des Repräsentantenhauses der Vereinigten Staaten für den 1. Kongressdistrikt des Bundesstaates Ohio. Biografie John Fassett Follett wurde im Franklin County in Vermont geboren. 1837 zog er mit seinen Eltern nach Ohio. Sie ließen sich dort im Licking County nieder. Er bes...

Deterioration of rocks and minerals through exposure to the elements This article is about weathering of rocks and minerals. For weathering of polymers, see Polymer degradation and Weather testing of polymers. For the public health concept, see Weathering hypothesis. A natural arch produced by erosion of differentially weathered rock in Jebel Kharaz (Jordan) Part of a series onGeologyScience of the solid Earth Index Outline Category Glossary History (Timeline) Key components Minerals Rock (Ig...

 

This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these messages) You can help expand this article with text translated from the corresponding article in German. (June 2024) Click [show] for important translation instructions. Machine translation, like DeepL or Google Translate, is a useful starting point for translations, but translators must revise errors as necessary and confirm that the translation is accu...