Photo by Patric Ho
This concise guide maps Python code smells to their corresponding design pattern solutions.
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" ]
Refactoring Examples in Python
This project translates refactoring examples from Refactoring to Patterns (Joshua Kerievsky) into Python. Each example shows original and refactored code, highlighting improvements. The refactoring process involved interpreting UML diagrams and adapting Java code to Python's nuances (handling cyclic imports and interfaces).
Example: Compose Method
The "Compose Method" refactoring simplifies complex code by extracting smaller, more meaningful methods.
# 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)
Example: Polymorphism (Test Automation)
This example demonstrates polymorphism in test automation, abstracting test setup for reusability.
# 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()
Example: Visitor Pattern
The Visitor pattern decouples classes from their methods.
# 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
Conclusion
This practical, hands-on approach to learning design patterns through refactoring significantly enhances understanding. The challenges encountered while translating the code solidify theoretical knowledge.
The above is the detailed content of Python: Refactoring to Patterns. For more information, please follow other related articles on the PHP Chinese website!

Python's flexibility is reflected in multi-paradigm support and dynamic type systems, while ease of use comes from a simple syntax and rich standard library. 1. Flexibility: Supports object-oriented, functional and procedural programming, and dynamic type systems improve development efficiency. 2. Ease of use: The grammar is close to natural language, the standard library covers a wide range of functions, and simplifies the development process.

Python is highly favored for its simplicity and power, suitable for all needs from beginners to advanced developers. Its versatility is reflected in: 1) Easy to learn and use, simple syntax; 2) Rich libraries and frameworks, such as NumPy, Pandas, etc.; 3) Cross-platform support, which can be run on a variety of operating systems; 4) Suitable for scripting and automation tasks to improve work efficiency.

Yes, learn Python in two hours a day. 1. Develop a reasonable study plan, 2. Select the right learning resources, 3. Consolidate the knowledge learned through practice. These steps can help you master Python in a short time.

Python is suitable for rapid development and data processing, while C is suitable for high performance and underlying control. 1) Python is easy to use, with concise syntax, and is suitable for data science and web development. 2) C has high performance and accurate control, and is often used in gaming and system programming.

The time required to learn Python varies from person to person, mainly influenced by previous programming experience, learning motivation, learning resources and methods, and learning rhythm. Set realistic learning goals and learn best through practical projects.

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Atom editor mac version download
The most popular open source editor

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools