重構手法之簡化條件表達式【2】

来源:http://www.cnblogs.com/liuyoung/archive/2017/11/27/7887082.html
-Advertisement-
Play Games

返回總目錄 本小節目錄 Consolidate Duplicate Conditional Fragments(合併重覆的條件片段) Remove Control Flag(移除控制標記) 3Consolidate Duplicate Conditional Fragments(合併重覆的條件片段) ...


返回總目錄

本小節目錄

3Consolidate Duplicate Conditional Fragments(合併重覆的條件片段)

概要

在條件表達式的每個分支上有著相同的一段代碼。

將這段重覆代碼搬到條件表達式之外。

動機

如果有一組條件表達式的所有分支都執行了相同的某段代碼,將這段代碼搬移到條件表達式外面。這樣才能更清楚地表明哪些東西隨條件的變化而變化、哪些東西保持不變。

範例

假如有如下代碼:

class Deal
{
    public double Price { get; set; }
    private bool IsSpecialDeal()
    {
        //your code here
        return true;
    }

    private void Send()
    {
        //your code here
    }

    public double GetTotalPrice()
    {
        double total;
        if (IsSpecialDeal())
        {
            total = Price * 0.95;
            Send();
        }
        else
        {
            total = Price * 0.98;
            Send();
        }
        return total;
    }
}

由於條件表達式的兩個分支都執行了Send()函數,所以將其移到條件表達式的外圍:

class Deal
{
    public double Price { get; set; }
    private bool IsSpecialDeal()
    {
        //your code here
        return true;
    }

    private void Send()
    {
        //your code here
    }

    public double GetTotalPrice()
    {
        double total;
        if (IsSpecialDeal())
        {
            total = Price * 0.95;
        }
        else
        {
            total = Price * 0.98;
        }
        Send();
        return total;
    }
}

這樣的重構手法同時也可以避免重覆代碼。

小結

我們在對待異常時,也是這樣做的。如果try塊和catch塊內都重覆執行了同一段代碼,可以將其移到finally塊內。

4Remove Control Flag(移除控制標記)

概要

在一系列布爾表達式中,某個變數帶著“控制標記”(control flag)的作用。

以break語句或return語句取代控制標記。

動機

在一系列條件表達式中,常常會看到用以判斷何時停止條件檢查的控制標記:

set done to false

while not done

  if(condition)

    do something

    set done to true

  next step of loop

這樣的控制標記大大降低了條件表達式的可讀性。以break語句或return語句取代控制標記,會帶來很大的便利。

範例:以break取代簡單的控制標記

下列函數用來檢查一系列人名之中是否包含兩個可疑人物的名字:

class Person
{
    public void CheckSecurity(string[] people)
    {
        bool found = false;
        foreach (var person in people)
        {
            if (!found)
            {
                if (person == "Don")
                {
                    SendAlert();
                    found = true;
                }
                if (person == "John")
                {
                    SendAlert();
                    found = true;
                }
            }
        }
    }

    private void SendAlert()
    {

    }
}

這種情況下很容易找出控制標記:當變數found被賦予true時,搜索就結束。這樣我們可以引入break語句替換掉對found變數賦值的語句,替換完成後刪除控制標記的引用:

class Person
{
    public void CheckSecurity(string[] people)
    {
        foreach (var person in people)
        {
            if (person == "Don")
            {
                SendAlert();
                break;
            }
            if (person == "John")
            {
                SendAlert();
                break;
            }
        }
    }

    private void SendAlert()
    {

    }
}

範例:以return返回控制標記

我們將上面的例子稍微改動下:

class Person
{
    public void CheckSecurity(string[] people)
    {
        string found = string.Empty;
        foreach (var person in people)
        {
            if (found == string.Empty)
            {
                if (person == "Don")
                {
                    SendAlert();
                    found = "Don";
                }
                if (person == "John")
                {
                    SendAlert();
                    found = "John";
                }
            }
        }
        OtherMethod(found);
    }

    private void SendAlert()
    {

    }

    private void OtherMethod(string found)
    {

    }
}

在這裡,變數found做了兩件事:既是控制標記,也是運算結果。遇到這種情況,一般都是先把計算found變數的代碼提煉到一個獨立函數中:

class Person
{
    public void CheckSecurity(string[] people)
    {
        string found = FoundMiscreant(people);
        OtherMethod(found);
    }

    private string FoundMiscreant(string[] people)
    {
        string found = string.Empty;
        foreach (var person in people)
        {
            if (person == "Don")
            {
                SendAlert();
                found = "Don";
            }
            if (person == "John")
            {
                SendAlert();
                found = "John";
            }
        }
        return found;
    }
    private void SendAlert()
    {

    }

    private void OtherMethod(string found)
    {

    }
}

然後以return語句取代控制語句,並且完全去掉控制標記:

class Person
{
    public void CheckSecurity(string[] people)
    {
        string found = FoundMiscreant(people);
        OtherMethod(found);
    }

    private string FoundMiscreant(string[] people)
    {
        foreach (var person in people)
        {
            if (person == "Don")
            {
                SendAlert();
                return "Don";
            }
            if (person == "John")
            {
                SendAlert();
                return "John";
            }
        }
        return string.Empty;
    }
    private void SendAlert()
    {

    }

    private void OtherMethod(string found)
    {

    }
}

如果返回值是void,也可以用return語句取代控制標記,只不過是一個空的return。

小結

如果以此辦法去處理帶有副作用的函數,需要先將查詢函數和修改函數分離。

 

To Be Continued……

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1 using System; 2 using System.Collections.Generic; 3 using System.Web; 4 using System.Web.Services; 5 using System.Data; 6 using Topevery.EOffice.Log ...
  • 原文http://www.360doc.com/content/13/0829/14/4513754_310723961.shtml 一、作用 AutoResetEvent和ManualResetEvent可用於控制線程暫停或繼續,擁有重要的三個方法:WaitOne、Set和Reset。 這三個方法 ...
  • 1.關於websphere MQ的常用名詞(針對Websphere MQ7.5版本) 隊列管理器:為應用程式提供消息傳遞服務的程式。使用消息隊列介面(MQI)的應用程式可以將消息放置到隊列並可從隊列中獲得消息,隊列管理器確保消息可以發送至正確的隊列或傳遞至另一個隊列管理器。 本地隊列:隊列管理器接收 ...
  • win+R輸入cmd,以管理員身份運行cmd; 安裝: cd C:\Windows\Microsoft.NET\Framework\v4.0.30319(InstallUtil.exe的路徑,註意InstallUtil.exe的版本號需要和項目的版本號相同)\InstallUtil.exe D:\d ...
  • 寫Code First 時(使用的是MySql資料庫),添加好EntityFrame、MySql.Data 、MySql.Data.Entity後 ,寫好TestDbContext類。 運行時報出一個"MySql.Data.MySqIClient.MySqlProviderSevices”違反了繼承 ...
  • 如圖,左圖是效果,右圖是原理,右圖X軸代表圖像一個像素點的灰度,Y軸代表RGB三個顏色對應的偽彩色圖顏色。代碼如下: for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Color c = bmp.GetPixel ...
  • 針對WCF分散式消息隊列MSMQ大大提高了處理能力,無論是發送方還是接收方都不用等待對方返回成功消息,但是不適合Client與Server端的實時交互。WCF分散式消息隊列,在處理日誌方面,效果還是很顯著的。當然,針對消息隊列的處理技術,有很多種,例如:ActiveMQ、RabbitMQ、ZeroM... ...
  • 演示產品下載地址:http://www.jinhusns.com ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...