控制圈复杂度的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

评论

  • M88回复

    Thanks a bunch for sharing this with all of us you actually know what you're talking about! Bookmarked. Kindly also visit my web site =). We could have a link exchange arrangement between us!

  • universalsitesupplies.co.uk回复

    you are truly a good webmaster. The web site loading velocity is incredible. It kind of feels that you are doing any unique trick. Moreover, The contents are masterwork. you've performed a magnificent process in this matter!

  • universalsitesupplies.co.uk回复

    Hi there, just became aware of your blog through Google, and found that it's truly informative. I’m gonna watch out for brussels. I’ll be grateful if you continue this in future. Many people will be benefited from your writing. Cheers!

  • universalsitesupplies.co.uk回复

    Nice post. I was checking constantly this blog and I'm impressed! Extremely helpful information particularly the last part 😊 I care for such information much. I was looking for this particular information for a long time. Thank you and best of luck.

  • Wanda回复

    You have a great blog here! Would you like to make some guest posts on my blog?

  • Melony回复

    Can I just say what a relief to find someone who actually knows what they are talking about.

  • dog food回复

    Hello would you mind stating which blog platform you're using? I'm going to start my own blog soon but I'm having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I'm looking for something completely unique. P.S Apologies for getting off-topic but I had to ask!|

  • Dog Walker回复

    Hey there! Would you mind if I share your blog with my facebook group? There's a lot of folks that I think would really appreciate your content. Please let me know. Thank you

  • Dog Walker Ottawa回复

    Hi, Neat post. There's a problem with your site in internet explorer, would test this… IE still is the market leader and a large portion of people will miss your excellent writing due to this problem.

  • Business Website回复

    Wow! Thank you! I permanently wanted to write on my site something like that. Can I take a part of your post to my website?

  • Internet Marketing回复

    I am not sure where you are getting your information, but good topic. I needs to spend some time learning more or understanding more. Thanks for fantastic information I was looking for this info for my mission.

  • Klingelanlage回复

    certainly like your website however you need to test the spelling on quite a few of your posts. Several of them are rife with spelling problems and I in finding it very troublesome to tell the truth nevertheless I will certainly come back again.|

  • Modern technology回复

    I am not sure where you are getting your info, but good topic. I needs to spend some time learning much more or understanding more. Thanks for wonderful information I was looking for this information for my mission.

  • Dog Walker Ottawa回复

    Hi there, just became alert to your blog through Google, and found that it is truly informative. I am gonna watch out for brussels. I will be grateful if you continue this in future. Lots of people will be benefited from your writing. Cheers!

  • SCAM回复

    Thank you so much for providing individuals with an exceptionally spectacular chance to read articles and blog posts from this website. It really is very fantastic and also full of a good time for me and my office friends to visit your web site the equivalent of 3 times a week to see the fresh tips you have. Of course, I am always impressed with the splendid knowledge you serve. Some 2 points in this article are unquestionably the most suitable I have had.

  • Latest technology回复

    There is clearly a bundle to know about this. I feel you made certain nice points in features also.

  • adidas ultra boost回复

    Thanks for every one of your hard work on this blog. My mom take interest in participating in investigations and it's easy to see why. Most people learn all concerning the powerful medium you present advantageous secrets on your website and as well cause participation from some other people on that subject and our own simple princess is without a doubt understanding a lot of things. Take pleasure in the remaining portion of the year. You are performing a fantastic job.

  • justbedding.com.au回复

    I've been browsing online more than three hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the web will be much more useful than ever before.

  • Dog Walker Ottawa回复

    Somebody essentially help to make critically articles I would state. That is the very first time I frequented your web page and up to now? I amazed with the analysis you made to create this actual post amazing. Fantastic job!

  • XXX回复

    Hello. Great job. I did not expect this. This is a impressive story. Thanks!

  • justbedding.com.au回复

    Terrific work! This is the type of information that should be shared around the internet. Shame on the search engines for not positioning this post higher! Come on over and visit my website . Thanks =)

  • Scam Website回复

    I gotta favorite this web site it seems very useful extremely helpful

  • Fake回复

    My coder is trying to persuade me to move to .net from PHP. I have always disliked the idea because of the costs. But he's tryiong none the less. I've been using WordPress on a number of websites for about a year and am worried about switching to another platform. I have heard fantastic things about blogengine.net. Is there a way I can import all my wordpress posts into it? Any help would be really appreciated!

  • justbedding.com.au回复

    Just wanna comment that you have a very nice website , I like the design and style it really stands out.

  • porn movies回复

    An impressive share, I just given this onto a colleague who was doing a little bit analysis on this. And he in reality purchased me breakfast as a result of I found it for him.. smile. So let me reword that: Thnx for the deal with! However yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying more on this topic. If possible, as you turn out to be experience, would you thoughts updating your weblog with extra details? It is extremely useful for me. Huge thumb up for this weblog post!

  • burun estetigi回复

    It's a shame you don't have a donate button! I'd certainly donate to this excellent blog! I suppose for now i'll settle for bookmarking and adding your RSS feed to my Google account. I look forward to brand new updates and will share this website with my Facebook group. Talk soon!|

  • Scam Website回复

    We are a group of volunteers and opening a new scheme in our community. Your site provided us with valuable information to work on. You've performed an impressive task and our whole community might be grateful to you.

  • Fake seller online回复

    Admiring the time and effort you put into your website and detailed information you provide. It's good to come across a blog every once in a while that isn't the same out of date rehashed information. Wonderful read! I've saved your site and I'm adding your RSS feeds to my Google account.

  • www.linux.ca回复

    Worқing ass a contract paralegal has components in its favor, and factorѕ wһicһ
    arre detrimental tto some people. If a wɑy of adventurе and excitеment inn your work ⅼife is what wоuld sᥙіt you the
    perfect, freellancing might be an incredіble option for you!

  • justbedding.com.au回复

    Super-Duper site! I am loving it!! Will come back again. I am taking your feeds also.

  • porn movies回复

    What i don't realize is in fact how you're now not actually much more well-favored than you might be right now. You are so intelligent. You understand thus significantly on the subject of this topic, produced me for my part believe it from a lot of varied angles. Its like men and women aren't involved until it¡¦s one thing to accomplish with Woman gaga! Your individual stuffs great. At all times maintain it up!

  • porn movies - qualityaluminumboatlifts.com回复

    With havin so much content do you ever run into any problems of plagorism or copyright violation? My blog has a lot of exclusive content I've either authored myself or outsourced but it looks like a lot of it is popping it up all over the internet without my agreement. Do you know any ways to help stop content from being stolen? I'd definitely appreciate it.

  • adidas nmd r1回复

    I simply wanted to develop a small message so as to say thanks to you for all of the splendid information you are posting here. My rather long internet investigation has now been compensated with useful facts and techniques to exchange with my co-workers. I 'd claim that most of us readers actually are unquestionably endowed to exist in a magnificent website with very many wonderful professionals with valuable suggestions. I feel rather fortunate to have discovered the web page and look forward to many more enjoyable moments reading here. Thanks a lot again for all the details.

  • Porn Online回复

    Hey There. I found your blog using msn. This is an extremely well written article. I will be sure to bookmark it and come back to read more of your useful info. Thanks for the post. I will definitely return.

  • photography website design回复

    I intended to post you that very small note to help say thanks a lot once again for the splendid information you have featured on this page. This is simply pretty generous of people like you to present unreservedly what a lot of people would have offered for an e-book in making some dough for themselves, notably now that you might have tried it if you ever desired. These tactics also served like a fantastic way to comprehend other people online have a similar fervor similar to mine to realize more on the subject of this matter. I am sure there are thousands of more pleasurable periods ahead for many who go through your blog.

  • web design logo回复

    I was just searching for this information for a while. After 6 hours of continuous Googleing, finally I got it in your website. I wonder what is the lack of Google strategy that do not rank this kind of informative web sites in top of the list. Normally the top sites are full of garbage.

  • Types Of Lawyers回复

    Great blog right here! Additionally your web site so much up fast! What host are you the use of? Can I am getting your affiliate link to your host? I wish my website loaded up as quickly as yours lol

  • Law School回复

    Hello. excellent job. I did not imagine this. This is a impressive story. Thanks!