搜尋
首頁後端開發Python教學Python:重構模式
Python:重構模式Jan 16, 2025 pm 01:10 PM

Python: Refactoring to Patterns

攝影:Patric Ho

這份簡明指南將 Python 程式碼氣味對應到對應的設計模式解決方案。

class CodeSmellSolutions:
    DUPLICATED_CODE = [
        "form_template_method",
        "introduce_polymorphic_creation_with_factory_method",
        "chain_constructors",
        "replace_one__many_distinctions_with_composite",
        "extract_composite",
        "unify_interfaces_with_adapter",
        "introduce_null_object",
    ]
    LONG_METHOD = [
        "compose_method",
        "move_accumulation_to_collecting_parameter",
        "replace_conditional_dispatcher_with_command",
        "move_accumulation_to_visitor",
        "replace_conditional_logic_with_strategy",
    ]
    CONDITIONAL_COMPLEXITY = [  # Complex conditional logic
        "replace_conditional_logic_with_strategy",
        "move_emblishment_to_decorator",
        "replace_state_altering_conditionals_with_state",
        "introduce_null_object",
    ]
    PRIMITIVE_OBSESSION = [
        "replace_type_code_with_class",
        "replace_state_altering_conditionals_with_state",
        "replace_conditional_logic_with_strategy",
        "replace_implict_tree_with_composite",
        "replace_implicit_language_with_interpreter",
        "move_emblishment_to_decorator",
        "encapsulate_composite_with_builder",
    ]
    INDECENT_EXPOSURE = [  # Lack of information hiding
        "encapsulate_classes_with_factory"
    ]
    SOLUTION_SPRAWL = [  # Scattered logic/responsibility
        "move_creation_knowledge_to_factory"
    ]
    ALTERNATIVE_CLASSES_WITH_DIFFERENT_INTERFACES = [  # Similar classes, different interfaces
        "unify_interfaces_with_adapter"
    ]
    LAZY_CLASS = [  # Insufficient functionality
        "inline_singleton"
    ]
    LARGE_CLASS = [
        "replace_conditional_dispatcher_with_command",
        "replace_state_altering_conditionals_with_state",
        "replace_implict_tree_with_composite",
    ]
    SWITCH_STATEMENTS = [  # Complex switch statements
        "replace_conditional_dispatcher_with_command",
        "move_accumulation_to_visitor",
    ]
    COMBINATION_EXPLOSION = [  # Similar code for varying data
        "replace_implicit_language_with_interpreter"
    ]
    ODDBALL_SOLUTIONS = [  # Multiple solutions for same problem
        "unify_interfaces_with_adapter"
    ]

Python 中的重構範例

專案將重構範例從 Refactoring to Patterns (Joshua Kerievsky) 翻譯成 Python。每個範例都顯示原始和重構的程式碼,突出顯示改進。 重構過程涉及解釋 UML 圖並使 Java 程式碼適應 Python 的細微差別(處理循環導入和介面)。

範例:撰寫方法

「Compose Method」重構透過擷取更小、更有意義的方法來簡化複雜的程式碼。

# Original (complex) code
def add(element):
    readonly = False
    size = 0
    elements = []
    if not readonly:
        new_size = size + 1
        if new_size > len(elements):
            new_elements = []
            for i in range(size):
                new_elements[i] = elements[i]  # Potential IndexError
            elements = new_elements
        size += 1
        elements[size] = element # Potential IndexError

# Refactored (simplified) code
def is_at_capacity(new_size, elements):
    return new_size > len(elements)

def grow_array(size, elements):
    new_elements = [elements[i] for i in range(size)] # List comprehension for clarity
    return new_elements

def add_element(elements, element, size):
    elements.append(element) # More Pythonic approach
    return len(elements) -1

def add_refactored(element):
    readonly = False
    if readonly:
        return
    size = len(elements)
    new_size = size + 1
    if is_at_capacity(new_size, elements):
        elements = grow_array(size, elements)
    size = add_element(elements, element, size)

範例:多態性(測試自動化)

此範例示範了測試自動化中的多態性,抽象化了測試設定以實現可重複使用性。

# Original code (duplicate setup)
class TestCase:
    pass

class DOMBuilder:
    def __init__(self, orders): pass
    def calc(self): return 42

class XMLBuilder:
    def __init__(self, orders): pass
    def calc(self): return 42

class DOMTest(TestCase):
    def run_dom_test(self):
        expected = 42
        builder = DOMBuilder("orders")
        assert builder.calc() == expected

class XMLTest(TestCase):
    def run_xml_test(self):
        expected = 42
        builder = XMLBuilder("orders")
        assert builder.calc() == expected

# Refactored code (polymorphic setup)
class OutputBuilder:
    def calc(self): raise NotImplementedError

class DOMBuilderRefac(OutputBuilder):
    def calc(self): return 42

class XMLBuilderRefac(OutputBuilder):
    def calc(self): return 42

class TestCaseRefac:
    def create_builder(self): raise NotImplementedError
    def run_test(self):
        expected = 42
        builder = self.create_builder()
        assert builder.calc() == expected

class DOMTestRefac(TestCaseRefac):
    def create_builder(self): return DOMBuilderRefac()

class XMLTestRefac(TestCaseRefac):
    def create_builder(self): return XMLBuilderRefac()

範例:訪客模式

訪客模式將類別與其方法解耦。

# Original code (conditional logic in TextExtractor)
class Node: pass
class LinkTag(Node): pass
class Tag(Node): pass
class StringNode(Node): pass

class TextExtractor:
    def extract_text(self, nodes):
        result = []
        for node in nodes:
            if isinstance(node, StringNode): result.append("string")
            elif isinstance(node, LinkTag): result.append("linktag")
            elif isinstance(node, Tag): result.append("tag")
            else: result.append("other")
        return result

# Refactored code (using Visitor)
class NodeVisitor:
    def visit_link_tag(self, node): return "linktag"
    def visit_tag(self, node): return "tag"
    def visit_string_node(self, node): return "string"

class Node:
    def accept(self, visitor): pass

class LinkTagRefac(Node):
    def accept(self, visitor): return visitor.visit_link_tag(self)

class TagRefac(Node):
    def accept(self, visitor): return visitor.visit_tag(self)

class StringNodeRefac(Node):
    def accept(self, visitor): return visitor.visit_string_node(self)

class TextExtractorVisitor(NodeVisitor):
    def extract_text(self, nodes):
        result = [node.accept(self) for node in nodes]
        return result

結論

這種透過重構學習設計模式的實用方法可以顯著增強理解。 翻譯程式碼時遇到的挑戰鞏固了理論知識。

以上是Python:重構模式的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
如何解決Linux終端中查看Python版本時遇到的權限問題?如何解決Linux終端中查看Python版本時遇到的權限問題?Apr 01, 2025 pm 05:09 PM

Linux終端中查看Python版本時遇到權限問題的解決方法當你在Linux終端中嘗試查看Python的版本時,輸入python...

我如何使用美麗的湯來解析HTML?我如何使用美麗的湯來解析HTML?Mar 10, 2025 pm 06:54 PM

本文解釋瞭如何使用美麗的湯庫來解析html。 它詳細介紹了常見方法,例如find(),find_all(),select()和get_text(),以用於數據提取,處理不同的HTML結構和錯誤以及替代方案(SEL)

python對象的序列化和避難所化:第1部分python對象的序列化和避難所化:第1部分Mar 08, 2025 am 09:39 AM

Python 對象的序列化和反序列化是任何非平凡程序的關鍵方面。如果您將某些內容保存到 Python 文件中,如果您讀取配置文件,或者如果您響應 HTTP 請求,您都會進行對象序列化和反序列化。 從某種意義上說,序列化和反序列化是世界上最無聊的事情。誰會在乎所有這些格式和協議?您想持久化或流式傳輸一些 Python 對象,並在以後完整地取回它們。 這是一種在概念層面上看待世界的好方法。但是,在實際層面上,您選擇的序列化方案、格式或協議可能會決定程序運行的速度、安全性、維護狀態的自由度以及與其他系

Python中的數學模塊:統計Python中的數學模塊:統計Mar 09, 2025 am 11:40 AM

Python的statistics模塊提供強大的數據統計分析功能,幫助我們快速理解數據整體特徵,例如生物統計學和商業分析等領域。無需逐個查看數據點,只需查看均值或方差等統計量,即可發現原始數據中可能被忽略的趨勢和特徵,並更輕鬆、有效地比較大型數據集。 本教程將介紹如何計算平均值和衡量數據集的離散程度。除非另有說明,本模塊中的所有函數都支持使用mean()函數計算平均值,而非簡單的求和平均。 也可使用浮點數。 import random import statistics from fracti

如何使用TensorFlow或Pytorch進行深度學習?如何使用TensorFlow或Pytorch進行深度學習?Mar 10, 2025 pm 06:52 PM

本文比較了Tensorflow和Pytorch的深度學習。 它詳細介紹了所涉及的步驟:數據準備,模型構建,培訓,評估和部署。 框架之間的關鍵差異,特別是關於計算刻度的

用美麗的湯在Python中刮擦網頁:搜索和DOM修改用美麗的湯在Python中刮擦網頁:搜索和DOM修改Mar 08, 2025 am 10:36 AM

該教程建立在先前對美麗湯的介紹基礎上,重點是簡單的樹導航之外的DOM操縱。 我們將探索有效的搜索方法和技術,以修改HTML結構。 一種常見的DOM搜索方法是EX

哪些流行的Python庫及其用途?哪些流行的Python庫及其用途?Mar 21, 2025 pm 06:46 PM

本文討論了諸如Numpy,Pandas,Matplotlib,Scikit-Learn,Tensorflow,Tensorflow,Django,Blask和請求等流行的Python庫,並詳細介紹了它們在科學計算,數據分析,可視化,機器學習,網絡開發和H中的用途

如何使用Python創建命令行接口(CLI)?如何使用Python創建命令行接口(CLI)?Mar 10, 2025 pm 06:48 PM

本文指導Python開發人員構建命令行界面(CLIS)。 它使用Typer,Click和ArgParse等庫詳細介紹,強調輸入/輸出處理,並促進用戶友好的設計模式,以提高CLI可用性。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),