控制圈复杂度的9种重构技术

一个软件总是为解决某种特定的需求而产生,时代在发展,客户的业务也在发生变化。有的需求相对稳定一些,有的需求变化的比较剧烈,还有的需求已经消失了,或者转化成了别的需求。在这种情况下,软件必须相应的改变。

考虑到成本和时间等因素,当然不是所有的需求变化都要在软件系统中实现。但是总的说来,软件要适应需求的变化,以保持自己的生命力。
这就产生了一种糟糕的现象:软件产品最初制造出来,是经过精心的设计,具有良好架构的。但是随着时间的发展、需求的变化,必须不断的修改原有的功能、追加新的功能,还免不了有一些缺陷需要修改。为了实现变更,不可避免的要违反最初的设计构架。经过一段时间以后,软件的架构就千疮百孔了。bug越来越多,越来越难维护,新的需求越来越难实现,软件的架构对新的需求渐渐的失去支持能力,而是成为一种制约。最后新需求的开发成本会超过开发一个新的软件的成本,这就是这个软件系统的生命走到尽头的时候。

重构就能够最大限度的避免这样一种现象。系统发展到一定阶段后,使用重构的方式,不改变系统的外部功能,只对内部的结构进行重新的整理。通过重构,不断的调整系统的结构,使系统对于需求的变更始终具有较强的适应能力。

重构可以降低项目的耦合度,使项目更加模块化,有利于项目的开发效率和后期的维护。让项目主框架突出鲜明,给人一种思路清晰,一目了然的感觉,其实重构是对框架的一种维护。

那么说到重构,可能我们普遍认为就是改改框架、使用一些最新流行的框架或者技术等等,我们到底要从哪些方面来对项目进行重构呢?下面我们进入主题:控制圈复杂度的9种重构技术
- 提炼函数

例子:如果某段代码可以被组织在一起并独立出来

void printOwing(double previousAmount)
 {
    Enumeration e = _orders.elements();
    double outstanding = previousAmount * 1.2;

      // 打印大标题
    System.out.println ("**************************");
    System.out.println ("***** Customer Owes ******");
    System.out.println ("**************************");

    // 计算未完成的订单数量
    while (e.hasMoreElements()) 
    {
        Order each = (Order) e.nextElement();
        outstanding += each.getAmount();
    }

    //打印明细
    System.out.println ("name:" + _name);
    System.out.println ("amount" + outstanding);
}

将这段代码放进一个独立函数中,并让函数名称解释该函数的用途

void printOwing(double previousAmount) 
{
    printBanner();
    double outstanding = getOutstanding(previousAmount * 1.2);
    printDetails(outstanding);
}

void printBanner() //打印大标题
{
    System.out.println ("**************************");
    System.out.println ("***** Customer Owes ******");
    System.out.println ("**************************");
}

// 计算未完成的订单数量
double getOutstanding(double initialValue) 
{
    double result = initialValue;
    Enumeration e = _orders.elements();
    while (e.hasMoreElements()) 
    {
        Order each = (Order) e.nextElement();
        result += each.getAmount();
    }
    return result;
}

void printDetails (double outstanding) //打印明细
 {
    System.out.println ("name:" + _name);
    System.out.println ("amount" + outstanding);
}
  • Substitute Algorithm(替换你的算法)

例子:
把当前算法重构成更清晰的算法

String foundPerson(String[] people)
{
    for (int i = 0; i < people.length; i++) 
    {
        if (people[i].equals ("Don"))
            return "Don";
        if (people[i].equals ("John"))
            return "John";
        if (people[i].equals ("Kent"))
            return "Kent";
    }
    return "";
}

重构成更清晰的算法

String foundPerson(String[] people)
{
    List candidates = Arrays.asList(new     
            String[]{"Don", "John","Kent"});
    for (int i=0; i<people.length; i++)
        if (candidates.contains(people[i]))
            return people[i];
    return "";
}
  • Decompose Conditional(分解条件式)

例子:你有一个复杂的条件语句

if (date.before (SUMMER_START) || date.after(SUMMER_END))
    charge = quantity * _winterRate + _winterServiceCharge;
else 
    charge = quantity * _summerRate;

从if、then、else三个段落中分别提炼出独立函数

if (notSummer(date))
    charge = winterCharge(quantity);
else 
    charge = summerCharge (quantity);
  • Consolidate Conditional Expression(合并条件式)

例子:你有一系列条件判断,都得到相同结果

double disabilityAmount() 
{
    if (_seniority < 2) return 0;
    if (_monthsDisabled > 12) return 0;
    if (_isPartTime) return 0;
    // compute the disability amount

将这些判断合并为一个条件式,并将这个条件式提炼成为一个独立函数,函数名自注释

double disabilityAmount() 
{
    if (isNotEligableForDisability()) return 0;
    // compute the disability amount
  • Consolidate Duplicate Conditional Fragments(合并重复的条件片断)

例子:在条件式的每个分支上有着相同的一段代码。

if (isSpecialDeal()) 
    {
        total = price * 0.95;
        send();
    }
else 
    {
        total = price * 0.98;
        send();
    }

将这段重复代码搬移到条件式之外,避免用拷贝粘贴的方式写重复代码

if (isSpecialDeal())
    total = price * 0.95;
else
    total = price * 0.98;
send();
  • Remove Control Flag(移除控制标记)

例子:当前代码使用标记变量,可读性差,容易出错

void checkSecurity(String[] people) {
    boolean found = false;
    for (int i = 0; i < people.length; i++) {
        if (! found) {
            if (people[i].equals ("Don")){
                sendAlert();
                found = true;
            }
            if (people[i].equals ("John")){
                   sendAlert();
                   found = true;
            }
        }
    }
}

以break和return取代标记变量

void checkSecurity(String[] people) {
    for (int i = 0; i < people.length; i++) {     
        if (people[i].equals ("Don")){
            sendAlert();
            break;
        }
        if (people[i].equals ("John")){
            sendAlert();
            break;
        }
    }
}
  • Separate Query from Modifier(将查询函数和修改函数分离)

例子:某个函数既返回对象状态值,又修改对象状态,建立两个不同的函数,其中一个负责查询,另一个负责修改



- Parameterize Method(令函数携带参数)

例子:若干函数做了类似的工作,但在函数本体中却
包含了不同的值

Dollars baseCharge()
 {
    double result = Math.min(lastUsage(),100) * 0.03;
    if (lastUsage() > 100) {
        result += (Math.min (lastUsage(),200) - 100) * 0.05;
    };
    if (lastUsage() > 200) {
        result += (lastUsage() - 200) * 0.07;
    };
    return new Dollars (result);
}

建立单一函数,以参数表达那些不同的值

Dollars baseCharge() 
{
    double result = usageInRange(0, 100) * 0.03;
    result += usageInRange (100,200) * 0.05;
    result += usageInRange (200, Integer.MAX_VALUE) * 0.07;
    return new Dollars (result);
}

int usageInRange(int start, int end) 
{
    if (lastUsage() > start) 
        return Math.min(lastUsage(),end) -start;
    else 
        return 0;
}

本文作者:Rance935本文出处:控制圈复杂度的9种重构技术转载请在开头注明作者详细信息和本文出处
欢迎关注我的微信公众号和QQ群,分享Android 开发和互联网内容
Android技术分享:群号534813930
微信号:androidparks
公众号:AndroidParks

评论

  • adidas ultra boost 3.0回复

    I am glad for commenting to make you understand of the fabulous encounter my cousin's daughter gained going through your blog. She figured out a lot of things, with the inclusion of what it is like to possess an ideal helping heart to let certain people smoothly learn about a number of complicated matters. You truly surpassed my desires. Many thanks for producing those effective, trustworthy, revealing and cool tips on the topic to Tanya.

  • CheplanovaGergo回复

    kann gunstig viagra bestellen

    http://viagralms.com/ - online viagra

    <a href="http://viagralms.com/">viagra online</a>

    100mg viagra too much

  • Itamar Serp回复

    My programmer is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the expenses. But he's tryiong none the less. I've been using WordPress on a variety of websites for about a year and am concerned about switching to another platform. I have heard great things about blogengine.net. Is there a way I can import all my wordpress content into it? Any kind of help would be greatly appreciated!|

  • CheplanovaGergo回复

    only now pfizer viagra 50mg

    http://viagralms.com/ - buy viagra online

    <a href="http://viagralms.com/">canadian viagra</a>

    pfizer viagra online bestellen

  • Online Education回复

    Excellent goods from you, man. I have understand your stuff previous to and you are just too excellent. I actually like what you have acquired here, certainly like what you're stating and the way in which you say it. You make it enjoyable and you still care for to keep it smart. I cant wait to read much more from you. This is really a wonderful site.

  • Civil Law回复

    Hi there, I found your site by means of Google while searching for a similar topic, your site got here up, it seems good. I've bookmarked it in my google bookmarks.

  • Landscape回复

    Magnificent website. Plenty of helpful info here. I¡¦m sending it to a few pals ans also sharing in delicious. And of course, thanks on your sweat!

  • MakritskayaGergo回复

    cipla viagra en linea

    <a href=http://viagraoail.com/>viagra cheap</a>

    <a href="http://viagraoail.com/">buy viagra online</a>

    mejor que viagra el-

  • VladilenGergo回复

    viagra 8cpr 50mg

    <a href=http://viagraomz.com/>generic viagra online</a>

    <a href="http://viagraomz.com/">generic viagra online</a>

    viagra teenage use

  • Law回复

    I have recently started a website, the information you provide on this website has helped me greatly. Thanks for all of your time & work.

  • travel promo回复

    Of course, what a splendid site and instructive posts, I surely will bookmark your website.Best Regards!

  • Homesearch回复

    I enjoy you because of each of your labor on this website. Kim really likes conducting investigations and it is easy to understand why. Most of us notice all regarding the powerful mode you render advantageous steps through the web blog and as well increase contribution from other individuals on this situation while my simple princess is now learning a lot of things. Enjoy the remaining portion of the year. You're carrying out a useful job.

  • Umanizzare presídios回复

    I'm not sure exactly why but this blog is loading incredibly slow for me. Is anyone else having this issue or is it a problem on my end? I'll check back later and see if the problem still exists.|

  • travel promo回复

    Definitely, what a magnificent website and instructive posts, I will bookmark your website.Have an awsome day!

  • Divorce回复

    I loved as much as you'll receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get bought an edginess over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly a lot often inside case you shield this hike.

  • Garden Ideas回复

    I'm still learning from you, but I'm trying to achieve my goals. I definitely love reading everything that is written on your website.Keep the information coming. I loved it!

  • Lelio Vieira Carneiro Junior回复

    Hello there, You've done an excellent job. I'll definitely digg it and personally suggest to my friends. I am sure they'll be benefited from this web site.|

  • VladilenGergo回复

    come comprare il viagra online

    <a href=http://viagraomz.com/>buy viagra</a>

    <a href="http://viagraomz.com/">buy generic viagra</a>

    can viagra be taken after food

  • adidas ultra回复

    I have to point out my passion for your kind-heartedness for folks that really need guidance on this particular question. Your special commitment to passing the solution along became incredibly beneficial and have constantly made men and women much like me to arrive at their targets. Your amazing interesting report denotes a whole lot a person like me and far more to my fellow workers. With thanks; from each one of us.

  • basketball shoes回复

    This is the best blog for anyone who desires to search out out about this topic. You realize a lot its virtually laborious to argue with you (not that I truly would need匟aHa). You definitely put a brand new spin on a subject thats been written about for years. Nice stuff, just great!

  • LenaGergo回复

    usa viagra 100mg

    <a href=http://norxcheapviagraf.com/>buy viagra</a>

    <a href="http://norxcheapviagraf.com/">generic viagra</a>

    viagra jelly vente

  • VladilenGergo回复

    pharmacy dubai selling viagra

    <a href=http://viagraomz.com/>cheap viagra online</a>

    <a href="http://viagraomz.com/">buy generic viagra</a>

    buy viagra over counter spain

  • Luiz Gastão Bittencourt回复

    I have read so many posts concerning the blogger lovers but this post is actually a pleasant paragraph, keep it up.|

  • Itamar Serp回复

    Hi! I could have sworn I've visited this site before but after looking at some of the articles I realized it's new to me. Anyhow, I'm certainly delighted I found it and I'll be bookmarking it and checking back frequently!|

  • yeezy boost回复

    I am just commenting to make you know what a wonderful discovery our daughter went through reading through your blog. She learned some things, most notably what it's like to have an incredible coaching spirit to have other folks easily thoroughly grasp some specialized subject areas. You truly surpassed our desires. Thanks for coming up with those helpful, trusted, explanatory and as well as fun thoughts on that topic to Tanya.

  • Nannik TV回复

    Very good article. I am going through a few of these issues as well..

  • buy surveillance cameras回复

    This paragraph provides clear idea designed for the new people
    of blogging, that actually how to do running a blog.

  • Wallets and wedges回复

    Great website. Lots of useful info here. I am sending it to several pals ans also sharing in delicious. And obviously, thanks for your sweat!

  • AV Surge Protectors & Power回复

    Hiya, I'm really glad I have found this info. Today bloggers publish only about gossips and internet and this is actually irritating. A good site with interesting content, that's what I need. Thanks for keeping this web-site, I'll be visiting it. Do you do newsletters? Cant find it.

  • Dress and Skirts回复

    I would like to show my passion for your kindness in support of persons that require guidance on this important content. Your special commitment to passing the message up and down appears to be exceedingly practical and has consistently enabled individuals much like me to realize their endeavors. Your personal warm and friendly report denotes this much a person like me and far more to my peers. Thanks a lot; from all of us.

  • Massage skin care回复

    Simply desire to say your article is as astounding. The clearness in your post is simply excellent and i could assume you are an expert on this subject. Fine with your permission let me to grab your RSS feed to keep up to date with forthcoming post. Thanks a million and please carry on the rewarding work.

  • Weight Training回复

    great issues altogether, you simply won a new reader. What could you recommend in regards to your post that you just made some days ago? Any certain?

  • Fitness skin care回复

    There is clearly a bunch to know about this. I believe you made various nice points in features also.

  • light up shoes回复

    I used to be very happy to search out this internet-site.I wished to thanks in your time for this excellent learn!! I undoubtedly enjoying every little little bit of it and I've you bookmarked to take a look at new stuff you weblog post.

  • José Wilame Araújo Rodrigues回复

    Hello, i believe that i saw you visited my weblog thus i came to go back the desire?.I am attempting to find things to improve my site!I guess its adequate to use some of your concepts!!|

  • กําจัดปลวก cs回复

    Hmm is anyone else encountering problems with the images on this blog loading?
    I'm trying to figure out if its a problem on my
    end or if it's the blog. Any feedback would be greatly appreciated.

  • About the Baby回复

    Hello, you used to write magnificent, but the last few posts have been kinda boring¡K I miss your tremendous writings. Past several posts are just a little bit out of track! come on!

  • Laptop Computers回复

    Useful information. Fortunate me I found your web site by chance, and I am shocked why this coincidence didn't happened earlier! I bookmarked it.

  • Automotive Industry回复

    hello!,I like your writing very much! share we keep in touch more approximately your article on AOL? I need an expert in this area to resolve my problem. May be that is you! Looking forward to peer you.

  • Laptop Reviews回复

    Wow, amazing blog format! How long have you ever been blogging for? you made running a blog glance easy. The full glance of your web site is wonderful, as well as the content material!

  • Baby Care回复

    I would like to show some appreciation to this writer just for rescuing me from this condition. Right after exploring throughout the the net and getting suggestions which are not pleasant, I assumed my entire life was over. Living minus the strategies to the problems you have solved through the blog post is a serious case, as well as those which could have adversely damaged my entire career if I had not discovered your web blog. Your good competence and kindness in dealing with every item was useful. I am not sure what I would've done if I had not discovered such a subject like this. I'm able to now look ahead to my future. Thanks very much for this high quality and amazing guide. I will not think twice to refer your blog post to any person who ought to have direction about this topic.

  • shopping tips回复

    Terrific work! This is the type of information that are meant to be shared across the internet. Shame on the seek engines for now not positioning this submit higher! Come on over and discuss with my site . Thanks =)

  • Yaramaz TV回复

    I truly appreciate this blog article.Much thanks again. Awesome.

  • best camera回复

    Good blog you've got here.. It's hard to find high-quality writing
    like yours these days. I truly appreciate people like you!
    Take care!!

  • 3D Glasses回复

    I've been absent for a while, but now I remember why I used to love this site. Thank you, I will try and check back more frequently. How frequently you update your web site?

  • Boots & booties回复

    I simply couldn't go away your web site prior to suggesting that I extremely enjoyed the usual information an individual supply to your visitors? Is going to be back steadily to investigate cross-check new posts